还在用 DateTime?我们已经用 LocalDateTime 啦!
孙玉超
2021-03-01 13:59:08
评论
500 浏览
收藏
0 赞
去年公司大佬就说了以后时间全部用 LocalDateTime ,当时没太在意,而且不太会用,还吐槽了一下。最近学习了一下 Java8 的时间相关类。“这饭真香……”
LocalDateTime
LocalDateTime 是不带时区的,不会存在时区问题,而且 Date 有的功能 LocalDateTime 完全能够满足,并且提供了可用的 API 和扩展功能。示例如下:
LocalDateTime time1= LocalDateTime.now();// 时间格式 2021-03-01T06:07:11.603Z LocalDateTime time2= LocalDateTime.now(); boolean after = time1.isAfter(time2);//比较两个时间,在另一个时间之后,还有之前,是否相同 LocalDateTime plusDays = time1.plusDays(1L);//可以加天,月,日,时……,也有相应的减法 LocalDateTime hour = time1.withHour(2);//用来重置当前时间的 年、月、日、时……
其他相关方法详见 API 。
Duration 和 Period
Duration 是计算两个时间的间隔,Period 是计算两个日期之间的间隔。示例如下:
LocalDateTime time1= LocalDateTime.now();// 时间格式 2021-03-01T06:07:11.603Z TimeUnit.SECONDS.sleep(5); //休眠五秒 LocalDateTime time2= LocalDateTime.now(); Duration duration = Duration.between(time1, time2);//获取两个时间的间隔,天,时,分,秒,毫秒,纳秒
TemporalAdjuster 和 TemporalAdjusters
TemporalAdjuster 是个函数式接口,叫做时间矫正器。用它来设置我们自己想要的时间。 TemporalAdjusters 是一个工具类,用来返回 TemporalAdjuster 实例,示例如下:
LocalDateTime time1= LocalDateTime.now();// 时间格式 2021-03-01T06:07:11.603Z
LocalDateTime with1 = time1.with(TemporalAdjusters.firstDayOfMonth());//可获取月/周第一天,最后一天等
LocalDateTime newTime = with1.with(temporal -> {
LocalDateTime temp = (LocalDateTime) temporal;
//写自己的业务逻辑
return temp;
});//TemporalAdjuster 是个函数式接口,表明我们可以使用lambda表达式来自定义我们想要的时间,比如下一个工作日,下一个结婚纪恋日等等总之 DateTime 有的功能,LocalDateTime 都有,Datetime 没有的功能,LocalDateTime 也有。