1.几个重要的类
LocalDate,LocalDateTime,LocalTime,Instant,Duration 以及 Period,TemporalAdjusters,DateTimeFormatter
2.本地时间
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()));
}
}
参考博客:
https://www.cnblogs.com/wupeixuan/p/11511915.html?utm_source=gold_browser_extension