如何获得日期之间的月数?

How to get number of months between dates?

在这个例子中 nownow + 2 months 之间的差异不等于 2,尽管我认为 LocalDate 数学是这样计算的:

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));
    }
}

输出:

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

我发现这个只是因为我碰巧 运行 一个单元测试的日期超出了预期...

正在查看 LocalDate.addMonths 的 javadoc:

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.

这意味着这是按预期工作的。所以不用诉诸 vintage Date/Time api...

获取两个日期之间的月数的正确方法是什么?

您可以使用 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)
    )
);

导入 java.time.temporal.ChronoUnitjava.time.YearMonth