Years between two dates

This example will demonstrate how to find the number of years between two dates using Java 8 date time api and Joda time. We will set the start date to December 25, 2004 and the end date to January 1, 2006. Then we will find the number of years between the start date and end date which equates to 1 year.

Java 8 Date and Time API

This snippet will find the difference between two dates in years using java 8 Duration.between and ChronoUnit.YEARS. Both approaches will calculate the amount of time between two temporal objects in the form of years.

@Test
public void years_between_two_dates_in_java_with_java8 () {

    LocalDate startDate = LocalDate.of(2004, Month.DECEMBER, 25);
    LocalDate endDate = LocalDate.of(2006, Month.JANUARY, 1);

    long numberOfYears = ChronoUnit.YEARS.between(startDate, endDate);
    assertEquals(1, numberOfYears);

    // or 

    long numberOfYears2 = Period.between(startDate, endDate).getYears();
    assertEquals(1, numberOfYears2);
}

Joda Time

Using joda, this snippet will calculate number of years between two dates using Years.yearsBetween.

@Test
public void years_between_two_dates_in_java_with_joda () {

    DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0);
    DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0);

    Years years = Years.yearsBetween(start, end);

    int numberOfYears = years.getYears();

    assertEquals(1, numberOfYears);
}