Calculate days between two Dates in Java 8 Calculate days between two Dates in Java 8 java java

Calculate days between two Dates in Java 8


If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:

LocalDate dateBefore;LocalDate dateAfter;long daysBetween = DAYS.between(dateBefore, dateAfter);

If you want literal 24 hour days, (a duration), you can use the Duration class instead:

LocalDate today = LocalDate.now()LocalDate yesterday = today.minusDays(1);// Duration oneDay = Duration.between(today, yesterday); // throws an exceptionDuration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option

For more information, refer to this document.


Based on VGR's comments here is what you can use:

ChronoUnit.DAYS.between(firstDate, secondDate)


You can use until():

LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);LocalDate christmas = LocalDate.of(2014, Month.DECEMBER, 25);System.out.println("Until christmas: " + independenceDay.until(christmas));System.out.println("Until christmas (with crono): " + independenceDay.until(christmas, ChronoUnit.DAYS));

Output:

Until christmas: P5M21DUntil christmas (with crono): 174

as mentioned at comment - first untill() returns Period.

Snippet from the documentation:

A date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'.
This class models a quantity or amount of time in terms of years, months, and days. See Duration for the time-based equivalent to this class.