How to get number of months between dates?

Viewed 123

The difference between now and now + 2 months not equal to 2 in this example, despite my thinking LocalDate math worked this way:

import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.MONTHS;

public class MyClass {
    public static void main(String... args) {
            LocalDate now = LocalDate.of(2020, 7, 31);
            LocalDate later = now.plusMonths(2);
            
            System.out.println("Now: " + now);
            System.out.println("Later: " + later);
            System.out.println("Months between now and later: " + MONTHS.between(now, later));
    }
}

Outputs:

Now: 2020-07-31
Later: 2020-09-30
Months between now and later: 1

I found this out only because I happened to run a unit test that fell on a date that breaks the expectation...

Reviewing the javadoc for LocalDate.addMonths:

This method adds the specified amount to the months field in three steps:

Add the input months to the month-of-year field
Check if the resulting date would be invalid
Adjust the day-of-month to the last valid day if necessary

For example, 2007-03-31 plus one month would result in the invalid date 2007-04-31. Instead of returning an invalid result, the last valid day of the month, 2007-04-30, is selected instead.

Meaning this is working as intended. So without resorting to the vintage Date/Time api...

What is the correct way to get the number of months between two dates?

1 Answers

You can use the YearMonth class to only consider years and months. Demo

System.out.println(
    "Months between now and later:"  + 
    ChronoUnit.MONTHS.between(
        YearMonth.from(now), 
        YearMonth.from(later)
    )
);

Import java.time.temporal.ChronoUnit and java.time.YearMonth.

Related