Calculating Days Between Dates in Java 8
In Java 8, calculating days between two dates can be achieved using the new Date API. To cater to specific requirements, this article presents a method that addresses two constraints: preventing errors from daylight saving time and accepting input as Date objects (without time information).
Logical Calendar Days
For calculating logical calendar days, the DAYS.between() method can be employed:
<code class="java">LocalDate dateBefore; LocalDate dateAfter; long daysBetween = DAYS.between(dateBefore, dateAfter);</code>
Literal 24-Hour Days (Duration)
If the requirement is to determine literal 24-hour days (a duration), the Duration class provides a suitable alternative:
<code class="java">LocalDate today = LocalDate.now() LocalDate yesterday = today.minusDays(1); // Duration oneDay = Duration.between(today, yesterday); // throws an exception Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option</code>
Additional Resources
For further details on the Java SE 8 Date and Time API, refer to this comprehensive guide: Java SE 8 Date and Time
The above is the detailed content of How to Calculate Days Between Dates in Java 8, Handling Daylight Saving Time and Date Objects?. For more information, please follow other related articles on the PHP Chinese website!