Months between two dates

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

Java 8 Date and Time API

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

public void months_between_two_dates_in_java_with_java8 () {

    LocalDate startDate = LocalDate.of(2004, Month.JANUARY, 1);
    LocalDate endDate = LocalDate.of(2005, Month.JANUARY, 1);

    long monthsInYear2 = ChronoUnit.MONTHS.between(startDate, endDate);

    assertEquals(12, monthsInYear2);

Joda Time

Using joda, this snippet will calculate number of months between two dates using Months.monthsBetween.

public void months_between_two_dates_in_java_with_joda () {

    DateTime start = new DateTime(2005, 1, 1, 0, 0, 0, 0);
    DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0);

    Months months = Months.monthsBetween(start, end);

    int monthsInYear = months.getMonths();

    assertEquals(12, monthsInYear);