Search code examples
javajava-8java-timedaysdate-difference

Calculate days between two Dates in Java 8


I know there are lots of questions on SO about how to get Dates in Java, but I want an example using new Java 8 Date API. I also know about the JodaTime library, but I want a method without relying on external libraries.

The function needs to be compliant with these restrictions:

  1. Prevent errors from date savetime
  2. Inputs are two Date objects (without time, I know about LocalDateTime, but I need to do this with Date instances)

Solution

  • 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: Java SE 8 Date and Time.