本文共 2901 字,大约阅读时间需要 9 分钟。
LocalDate,LocalDateTime,LocalTime,Instant,Duration 以及 Period,TemporalAdjusters,DateTimeFormatter
LocalDate,LocalDateTime,LocalTime这三个为本地时间,生日,假日,计划等通常都会表示成本地时间,创建和使用的方法都差不多。
LocalDate的作用:创建时间,增加或减去年月日天周,修改年月日,获取年月日周,判断是否为闰年,比较两个时间
将时间格式化后进行比较:
public void checkSendDate(Date sendDate) { //发送时间选择将来 Instant instant = sendDate.toInstant(); ZoneId zoneId = ZoneId.systemDefault(); LocalDateTime nowLocalDateTime = LocalDateTime.now(); LocalDateTime sendLocalDateTime = instant.atZone(zoneId).toLocalDateTime(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); String strNowLocalDateTime = nowLocalDateTime.format(formatter); String strSendLocalDateTime = sendLocalDateTime.format(formatter); nowLocalDateTime = LocalDateTime.parse(strNowLocalDateTime, formatter); sendLocalDateTime = LocalDateTime.parse(strSendLocalDateTime, formatter); if (sendLocalDateTime.isBefore(nowLocalDateTime)) { throw new CommonException("error.send.time"); } }
控制两个时间之间的间隔:
public void checkQueryByDate(ArtCalendarEventVO artCalendarEventVO) { ZoneId zoneId = ZoneId.systemDefault(); if (artCalendarEventVO.getStartDate() != null && artCalendarEventVO.getEndDate() != null) { LocalDate startDate = artCalendarEventVO.getStartDate().toInstant().atZone(zoneId).toLocalDate(); LocalDate endDate = artCalendarEventVO.getEndDate().toInstant().atZone(zoneId).toLocalDate(); if (endDate.toEpochDay() - startDate.toEpochDay() > 180) { throw new CommonException("error.lastTime.too.long"); } } if (artCalendarEventVO.getStartDate() != null && artCalendarEventVO.getEndDate() == null) { LocalDateTime localDateTime = artCalendarEventVO.getStartDate().toInstant().atZone(zoneId).toLocalDateTime(); artCalendarEventVO.setEndDate(Date.from(localDateTime.plusDays(180).atZone(zoneId).toInstant())); } if (artCalendarEventVO.getEndDate() != null && artCalendarEventVO.getStartDate() == null) { LocalDateTime localDateTime = artCalendarEventVO.getEndDate().toInstant().atZone(zoneId).toLocalDateTime(); artCalendarEventVO.setStartDate(Date.from(localDateTime.minusDays(180).atZone(zoneId).toInstant())); } }
时间线Instant,表示时间线上的某一时刻,有最大值,最小值,这个类还可以比较,并且他得到的时间是所谓的带时区的UTC时间。
Duration:表示两个绝对时间之间的度量
这两个类都是final类,所做的时间的操作都是返回一个新的对象。
人类时间LocalDate带有年月日的日期。
除了可以在LocalDate对象上加减时间,时间段以外,还可以通过isBefor,isAfter方法比较时间 以及判断是否闰年。
Period表示两个本地时间的间隔。
TemporalAdjusters 日期调整期类, 除了提供的默认的调整器类,还可以通过实现TemporalAdjuster接口来自己写一个调整器。
从给定日期起下一个星期三的日期。
现在自己写一个日期调整器获取下一个工作日:
可以发现TemporalAdjuster是一个函数式的接口,所以可以传一个lambda表达式。
第二个本地时间LocalTime,表示当日的时刻
LocalDateTime表示日期和时间。
如果想要时间带上时区,那么就要使用ZonedDateTime类,相当于Calendar
DateTimeFormatter
参考博客:
转载地址:http://eahhz.baihongyu.com/