Home  >  Article  >  Java  >  How to Calculate Days Between Dates in Java 8, Handling Daylight Saving Time and Date Objects?

How to Calculate Days Between Dates in Java 8, Handling Daylight Saving Time and Date Objects?

Linda Hamilton
Linda HamiltonOriginal
2024-11-06 00:32:02802browse

How to Calculate Days Between Dates in Java 8, Handling Daylight Saving Time and Date Objects?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn