eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments