简体   繁体   中英

How to get number of months between dates?

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM