java.util.Date类总结
1.创建对象
Date date = new Date();
System.out.println( date );
结果
Mon Jul 20 11:54:38 CST 2020
2.调用System.currentTimeMillis()方法返回当前时间距离1970-1-1 00:00:00 经过的毫秒数
long timeMillis = System.currentTimeMillis();
System.out.println( timeMillis );
结果
1595250425781
3.也可以根据毫秒数返回DATA对象
Date date2 = new Date(timeMillis);
System.out.println( date2);
date2 = new Date(1000) ;
System.out.println( date2 );
结果
Mon Jul 20 21:07:05 CST 2020
Thu Jan 01 08:00:01 CST 1970//CST中国时间距离世界协调时有8个小时的时差
4.对日期格式化,创建SimpleDateFormat对象,在构造方法中指定日期的格式
然后调用SimpleDateFormat对象的format(Date)可以把Date日期转换为字符串
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String ss = sdf.format(date);
System.out.println( ss );
结果
2020-07-20 21:12:01
5.把字符串转换为DATA对象,先根据日期字符串的格式创建SimpleDateFormat对象,调用parse(String)可以把字符串转换为日期
String text = "2066年5月1日 8:25:28";
SimpleDateFormat another = new SimpleDateFormat("yyyy年M月d日 H:mm:ss");
Date date2 = another.parse(text);
System.out.println( date2 );
结果
Sat May 01 08:25:28 CST 2066
现在介绍一些线程安全的方法,java.time包
1.创建LocalDateTime对象,返回当前日期. 注意LocalDateTime()构造方法是私有的, 不能new 构造方法的形式创建对象. LocalDateTime类提供了静态方法now()返回当前日期对象
LocalDateTime dateTime = LocalDateTime.now();
System.out.println( dateTime );
结果
2020-07-20T21:16:27.234
2.也可以调用 LocalDateTime类的静态方法of( 年, 月, 日, 小时, 分钟, 秒)返回一个指定的日期
LocalDateTime localDateTime2 = LocalDateTime.of(2066, 11, 12, 11, 28,56);
System.out.println( localDateTime2 );
结果
2066-11-12T11:28:56
3.使用DateTimeFormatter类对日期格式化, 调用DateTimeFormatter类的静态方法ofPaatern( 格式串 ) 返回一个对象,调用 LocalDateTime 对象的实例方法format实现日期 的格式化
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String ss = dateTime.format(dateTimeFormatter);
System.out.println( ss );
结果
2020-07-20 21:16:27
4.把字符串转换为LocalDateTime对象,根据 字符串创建 DateTimeFormatter 对象,调用 LocalDateTime 类的静态方法,parse()可以把字符串转换为日期对象
String txt = "2068年2月12日 5:28:36";
DateTimeFormatter another = DateTimeFormatter.ofPattern("yyyy年M月dd日 H:mm:ss");
localDateTime2 = LocalDateTime.parse(txt, another);
System.out.println( localDateTime2 );
结果
2068-02-12T05:28:36