Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Calculating month intervals between dates is a common programming task. The Java standard library and third-party libraries provide classes and methods to calculate months between two dates.

In this tutorial, we’ll delve into details of how to use the legacy Date API, Date Time API, and Joda-Time library to calculate month intervals between two dates in Java.

2. Impact of Day Value

When calculating the month interval between two dates, the day value of the dates impacts the result.

By default, the Java standard library and Joda-Time library consider the day value. If the day value of the end date is less than the day value of the start day, the final month isn’t counted as a full month and is excluded from the month interval:

LocalDate startDate = LocalDate.parse("2023-05-31");
LocalDate endDate = LocalDate.parse("2023-11-28");

In the code above, the day value of the end date is less than the day value of the start date. Therefore, the final month won’t count as a full month.

However, if the day value of the end date is equal to or greater than the day value of the day value of the start date, the final month is considered a full month and included in the interval:

LocalDate startDate = LocalDate.parse("2023-05-15");
LocalDate endDate = LocalDate.parse("2023-11-20");

In some cases, we may decide to ignore the day value completely and only consider the month value difference between the two dates.

In the subsequent sections, we’ll see how to calculate month intervals between two dates with or without considering the day value.

3. Using Legacy Date API

When using the legacy Date API, we need to create a custom method to calculate month intervals between two dates. With the Calendar class, we can calculate the month interval between two dates using the Date class.

3.1. Without the Day Value

Let’s write a method that uses the Calendar and Date classes to calculate the month interval between two Date objects without considering the day value:

int monthsBetween(Date startDate, Date endDate) {
    if (startDate == null || endDate == null) {
        throw new IllegalArgumentException("Both startDate and endDate must be provided");
    }

    Calendar startCalendar = Calendar.getInstance();
    startCalendar.setTime(startDate);
    int startDateTotalMonths = 12 * startCalendar.get(Calendar.YEAR) 
      + startCalendar.get(Calendar.MONTH);

    Calendar endCalendar = Calendar.getInstance();
    endCalendar.setTime(endDate);
    int endDateTotalMonths = 12 * endCalendar.get(Calendar.YEAR) 
      + endCalendar.get(Calendar.MONTH);

    return endDateTotalMonths - startDateTotalMonths;
}

This method takes the start date and end date as arguments. First, we create a Calendar instance and pass the Date object to it. Next, we calculate the total months of each date by converting the year to month and adding it to the current month value.

Finally, we find the difference between the two dates.

Let’s write a unit test for the method:

@Test
void whenCalculatingMonthsBetweenUsingLegacyDateApi_thenReturnMonthsDifference() throws ParseException {
    MonthInterval monthDifference = new MonthInterval();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    
    Date startDate = sdf.parse("2016-05-31");
    Date endDate = sdf.parse("2016-11-30");
    int monthsBetween = monthDifference.monthsBetween(startDate, endDate);
    
    assertEquals(6, monthsBetween);
}

In the code above, we create a SimpleDateFormat object to format the date. Next, we pass the Date object to the monthsBetween() to calculate the month interval.

Finally, we assert that the output is equal to the expected result.

3.2. With the Day Value

Also, let’s see an example code that puts the day value into consideration:

int monthsBetweenWithDayValue(Date startDate, Date endDate) {
    if (startDate == null || endDate == null) {
        throw new IllegalArgumentException("Both startDate and endDate must be provided");
    }
    
    Calendar startCalendar = Calendar.getInstance();
    startCalendar.setTime(startDate);
    
    int startDateDayOfMonth = startCalendar.get(Calendar.DAY_OF_MONTH);
    int startDateTotalMonths = 12 * startCalendar.get(Calendar.YEAR) 
      + startCalendar.get(Calendar.MONTH);
        
    Calendar endCalendar = Calendar.getInstance();
    endCalendar.setTime(endDate);
    
    int endDateDayOfMonth = endCalendar.get(Calendar.DAY_OF_MONTH);
    int endDateTotalMonths = 12 * endCalendar.get(Calendar.YEAR) 
      + endCalendar.get(Calendar.MONTH);

    return (startDateDayOfMonth > endDateDayOfMonth) 
      ? (endDateTotalMonths - startDateTotalMonths) - 1 
      : (endDateTotalMonths - startDateTotalMonths);
}

Here, we add a condition to check if the start date day value is greater than the end date day value. Then, we adjust the month interval based on the condition.

Here’s a unit test for the method:

@Test
void whenCalculatingMonthsBetweenUsingLegacyDateApiDayValueConsidered_thenReturnMonthsDifference() throws ParseException {
    MonthInterval monthDifference = new MonthInterval();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    
    Date startDate = sdf.parse("2016-05-31");
    Date endDate = sdf.parse("2016-11-28");
    int monthsBetween = monthDifference.monthsBetweenWithDayValue(startDate, endDate);
    
    assertEquals(5, monthsBetween);
}

Since the end date day value is less than the start date day value, the final month doesn’t count as a full month.

4. Using the Date Time API

Since Java 8, the Date Time API provides options to get the month interval between two dates. We can use the Period class and ChronoUnit enum to compute the month interval between two dates.

4.1. The Period Class

The Period class provides a static method named between() to calculate month intervals between two dates. It accepts two arguments representing the start date and the end date. The day value of the date impacts the month interval when using the Period class:

@Test
void whenCalculatingMonthsBetweenUsingPeriodClass_thenReturnMonthsDifference() {
    Period diff = Period.between(LocalDate.parse("2023-05-25"), LocalDate.parse("2023-11-23"));
    assertEquals(5, diff.getMonths());
}

Considering the day’s value in the dates, between() returns a difference of five months. The day value of the end date is less than the day value of the start date. Hence, the final month doesn’t count as a full month.

However, if we intend to ignore the day value of the dates, we can set the LocalDate objects to the first day of the month:

@Test
void whenCalculatingMonthsBetweenUsingPeriodClassAndAdjsutingDatesToFirstDayOfTheMonth_thenReturnMonthsDifference() {
    Period diff = Period.between(LocalDate.parse("2023-05-25")
      .withDayOfMonth(1), LocalDate.parse("2023-11-23")
      .withDayOfMonth(1));
    assertEquals(6, diff.getMonths());
}

Here, we invoke the withDayOfMonth() method on the LocalDate object to set the dates to the beginning of the month.

4.2. The ChronoUnit Enum

The ChronoUnit enum provides a constant named MONTHS and a static method named between() to compute the month interval between two dates.

Similar to the Period class, the ChronoUnit enum also considers the day value in the two dates:

@Test
void whenCalculatingMonthsBetweenUsingChronoUnitEnum_thenReturnMonthsDifference() {
    long monthsBetween = ChronoUnit.MONTHS.between(
      LocalDate.parse("2023-05-25"), 
      LocalDate.parse("2023-11-23")
    );
    assertEquals(5, monthsBetween);
}

Also, if we intend to ignore the day value, we can set the date objects to the first day of the month using the withDayOfMonth() method:

@Test
void whenCalculatingMonthsBetweenUsingChronoUnitEnumdSetTimeToFirstDayOfMonth_thenReturnMonthsDifference() {
    long monthsBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2023-05-25")
      .withDayOfMonth(1), LocalDate.parse("2023-11-23")
      .withDayOfMonth(1));
    assertEquals(6, monthsBetween);
}

Finally, we can also use YearMonth.from() method with ChronoUnit enum to ignore the day value:

@Test
void whenCalculatingMonthsBetweenUsingChronoUnitAndYearMonth_thenReturnMonthsDifference() {
    long diff = ChronoUnit.MONTHS.between(
      YearMonth.from(LocalDate.parse("2023-05-25")), 
      LocalDate.parse("2023-11-23")
    );
    assertEquals(6, diff);
}

In the code above, we use the YearMonth.from() method to consider only the year and month values while computing the month between the two dates.

5. Using the Joda Time Library

The Joda-Time library provides the Months.monthsBetween() method to find month intervals between two dates. To use the Joda-Time library, let’s add its dependency to the pom.xml:

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.12.5</version>
</dependency>

Just like the Date Time API, it considers the day value of the dates objects by default:

@Test
void whenCalculatingMonthsBetweenUsingJodaTime_thenReturnMonthsDifference() {
    DateTime firstDate = new DateTime(2023, 5, 25, 0, 0);
    DateTime secondDate = new DateTime(2023, 11, 23, 0, 0);
    int monthsBetween = Months.monthsBetween(firstDate, secondDate).getMonths();
    assertEquals(5, monthsBetween);
}

In the code above, we create two date objects with a set date. Next, we pass the date objects to the monthsBetween() method and invoke getMonths() on it.

Finally, we assert that the return month interval is equal to the expected value.

If we intend not to consider the day value, we can invoke the withDayOfMonth() method on the DateTime objects and set the day to the first day of the month:

@Test
void whenCalculatingMonthsBetweenUsingJodaTimeSetTimeToFirstDayOfMonth_thenReturnMonthsDifference() {
    DateTime firstDate = new DateTime(2023, 5, 25, 0, 0).withDayOfMonth(1);
    DateTime secondDate = new DateTime(2023, 11, 23, 0, 0).withDayOfMonth(1);
        
    int monthsBetween = Months.monthsBetween(firstDate, secondDate).getMonths();
    assertEquals(6, monthsBetween);
}

Here, we set the day of the two date objects to the first day of the month to avoid the day value impacting the expected result.

6. Conclusion

In this article, we learned ways of calculating the month interval between two date objects using the standard library and a third-party library. Also, we saw how to calculate month intervals between dates with and without considering the day value of the dates.

The choice to include or ignore the day value depends on our goal and specific requirements. Also, the Date Time API provides different options, and it’s recommended because it’s easier to use and doesn’t require external dependency.

As usual, the complete source code for the examples is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.