计算两个时间之间相差⼏天、⽉、年ChronoUnit类
//获取当前时间(2021-06-22)
LocalDate today = w();
//将String转LocalDateTime
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
string转date的方法
LocalDate collectTimeDate = LocalDate.parse("2021-05-01",df);
//判断相差多少天
log.info("ChronoUnit====相差{}年,相差{}⽉,相差{}天",
ChronoUnit.YEARS.between(collectTimeDate,today),
ChronoUnit.MONTHS.between(collectTimeDate,today),
ChronoUnit.DAYS.between(collectTimeDate,today));
注意:若调⽤获取时、分、秒、半天⽅法皆报错
结果:
//获取当前时间(2021-06-22 17:27:03)
LocalDateTime today = w();
//将String转LocalDateTime
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime collectTimeDate = LocalDateTime.parse("2021-05-01 16:40:23",df);
//判断相差多少天
log.info("ChronoUnit====相差{}年,相差{}⽉,相差{}天",
ChronoUnit.YEARS.between(collectTimeDate,today),
ChronoUnit.MONTHS.between(collectTimeDate,today),
ChronoUnit.DAYS.between(collectTimeDate,today));
log.info("ChronoUnit====相差{}⼩时,相差{}分钟,相差{}秒",
ChronoUnit.HOURS.between(collectTimeDate,today),
ChronoUnit.MINUTES.between(collectTimeDate,today),
ChronoUnit.SECONDS.between(collectTimeDate,today));
log.info("ChronoUnit====相差{}半天",ChronoUnit.HALF_DAYS.between(collectTimeDate,today));
结果:
Period类
//获取当前时间(2021-06-22)
LocalDate todayDate = w();
//将String转LocalDateTime
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate lastDate = LocalDate.parse("2021-05-01",dtf);
//判断相差多少天
log.info("Period====相差{}年,相差{}⽉,相差{}天",
Period.between(lastDate,todayDate).getYears(),
Period.between(lastDate,todayDate).getMonths(),
Period.between(lastDate,todayDate).getDays());
注意:Period.between⽅法只接收LocalDate类型的传参
结果:
从结果中可看到,两个时间本是相差52天,但此处只显⽰相差21天;因为此处只⽤两者的⽇相减,不管年份和⽉份Duration类
//获取当前时间(2021-06-22 17:27:03)
LocalDateTime currentDate = w();
//将String转LocalDateTime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = LocalDateTime.parse("2021-05-01 16:40:23",formatter);
log.info("Duration====相差{}天,相差{}⼩时,相差{}分钟",
Duration.between(date,currentDate).toDays(),
Duration.between(date,currentDate).toHours(),
Duration.between(date,currentDate).toMinutes());
结果:
以下这种会报错:
//获取当前时间(2021-06-22)
LocalDate currentDate = w();
//将String转LocalDate
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");        LocalDate date = LocalDate.parse("2021-05-01",formatter);
//判断相差多少天
log.info("Duration====相差{}天", Duration.between(date,currentDate).toDays());结果:
综上,推荐使⽤ChronoUnit类

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。