Home > Java > javaTutorial > 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
Release: 2024-11-06 00:32:02
Original
888 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template