java获取当前本地日期时间

时间:2024-12-13 21:32:13

jdk1.8 提供新的日期操作方式

	import org.junit.Test;
	import java.time.LocalDateTime;
	import java.time.format.DateTimeFormatter;
	@Test
    public void test5() {
        // jdk1.8 提供 LocalDate LocalTime LocalDateTime DateTimeFormatter
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("格式化: " + localDateTime.format(dtf));
        System.out.println("年份: " + localDateTime.getYear());
        System.out.println("当前年份中第多少天(1-365 or 1-366): " + localDateTime.getDayOfYear());
        System.out.println("英文表示月份: " + localDateTime.getMonth());
        System.out.println("以数字的方式表示月份(1-12): " + localDateTime.getMonthValue());
        System.out.println("当前月份中第几天(1-31): " + localDateTime.getDayOfMonth());
        System.out.println("星期几: " + localDateTime.getDayOfWeek());
        System.out.println("小时: " + localDateTime.getHour());
        System.out.println("分钟: " + localDateTime.getMinute());
        System.out.println("秒: " + localDateTime.getSecond());
        // 指定日期
        LocalDateTime ldt = LocalDateTime.of(2020, 1, 26, 8, 30, 30);
        // 获取年月日
        System.out.println(ldt.toLocalDate());
        // 获取时分秒
        System.out.println(ldt.toLocalTime());
    }

jdk1.8 之前

  • 方法一
import .*;
import .*;
public class HelloDate{
	public static void main(String[] args){
		Date date = new Date();
		/*
		* ()为获取当前日期
		* ()为获取当前时间
		* ()为获取当前日期时间
		* 
		*/
		DateFormat df = ();
		SimpleDateFormat sdf = (SimpleDateFormat)();
		("当前日期时间:" + (date));
		("当前日期时间:" + (date));
		
		// out: 当前日期时间:2018-6-10 11:50:03
	}
}
  • 方法二
Calendar calendar= ();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
((()));

  • 方法三
Calendar calendar = ();      
int year = ();      
int month = ();      
int day = ();      
int hour = (Calendar.HOUR_OF_DAY);      
int minute = ();      
int second = ();
      
("现在是" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒");