Calculate days between two dates in Java 8

Marcos picture Marcos · Nov 19, 2014 · Viewed 247.5k times · Source

I know there are lots of questions on SO about how to get, but I want and example using new Java 8 Date api. I also know JodaTime library, but I want a work way without external libraries.

Function needs to complain with these restrictions:

  1. Prevent errors from date savetime
  2. Input are two Date's objects (without time, I know localdatetime, but I need to do with date instances)

Answer

syntagma picture syntagma · Nov 19, 2014

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 exception
Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option

For more information, refer to this document.