Days between two dates

This example shows how to find how many days are between two dates using Java 8 date time api and Joda time. We will first subtract 1 day from the current date and then find the days between the start and end date. In a comparable example we demonstrate how to find the difference between two dates in days using groovy.

Java 8 Date and Time API

This snippet will calculate days between two dates using java 8 Period.between and ChronoUnit.DAYS.between. Each approach will calculate the amount of time between two temporal objects in the form of days. Something to note, a ChronoUnit gives an absolute count of days, whereas Period is an abstraction for more units than just the day.

@Test
public void days_between_two_dates_in_java_with_java8 () {

    LocalDate startDate = LocalDate.now().minusDays(1);
    LocalDate endDate = LocalDate.now();

    long days = Period.between(startDate, endDate).getDays();
    assertEquals(1, days);

    // or 

    long days2 = ChronoUnit.DAYS.between(startDate, endDate);
    assertEquals(1, days2);
}

Joda Time

This snippet will find the difference between two dates in the number of days using joda.

@Test
public void days_between_two_dates_in_java_with_joda () {

    // start day is 1 day in the past
    DateTime startDate = new DateTime().minusDays(1);
    DateTime endDate = new DateTime();

    Days d = Days.daysBetween(startDate, endDate);
    int days = d.getDays();

    assertEquals(1, days);
}