java.util.Date Calculate difference in days

前端 未结 1 1146
清歌不尽
清歌不尽 2020-12-06 13:19

I tried to calculate the difference between two dates and I noticed one thing. When calculating only the days, the start of daylight saving time is included in the interval,

相关标签:
1条回答
  • 2020-12-06 14:20

    Oh yes a better solution there is!

    Stop using the outmoded java.util.Date class and embrace the power of the java.time API built into Java 8 and later (tutorial). Specifically, the DateTimeFormatter, LocalDate, and ChronoUnit classes.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
    LocalDate date1 = LocalDate.parse("03-29-2015", formatter);
    LocalDate date2 = LocalDate.parse("03-30-2015", formatter);
    long days = ChronoUnit.DAYS.between(date1, date2);
    System.out.println(days); // prints 1
    
    0 讨论(0)
提交回复
热议问题