Home >Java >javaTutorial >How do you calculate the days between two dates in Java 8?

How do you calculate the days between two dates in Java 8?

Linda Hamilton
Linda HamiltonOriginal
2024-11-11 15:04:02546browse

How do you calculate the days between two dates in Java 8?

How to Calculate Days Between Two Dates in Java 8

Calculating the number of days between two dates is a common task in programming. In Java 8, this can be accomplished using the new Date API without the need for external libraries.

Requirements:

  • Prevent errors from date savings time.
  • Inputs are two Date objects without time.

Solution without External Libraries:

For Logical Calendar Days:

Use the ChronoUnit.DAYS.between() method:

<code class="java">LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter);</code>

For Literal 24-Hour Days:

Use the Duration class:

<code class="java">LocalDate today = LocalDate.now();
LocalDate yesterday = today.minusDays(1);
Duration duration = Duration.between(today.atStartOfDay(), yesterday.atStartOfDay());
long daysBetween = duration.toDays();</code>

Note that the Duration.between() method throws an exception if the start time is after the end time. To avoid this, subtract the end time from the start time before passing it to Duration.between().

For more detailed information and alternative methods, refer to the Java SE 8 Date and Time documentation.

The above is the detailed content of How do you calculate the days between two dates in Java 8?. 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