简体   繁体   English

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

[英]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:在这个例子中, 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));
    }
}

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:查看 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.例如,2007-03-31 加上一个月将导致无效日期 2007-04-31。 Instead of returning an invalid result, the last valid day of the month, 2007-04-30, is selected instead.代替返回无效结果,而是选择该月的最后一个有效日期 2007-04-30。

Meaning this is working as intended.这意味着这是按预期工作的。 So without resorting to the vintage Date/Time api...因此,无需求助于老式日期/时间 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.您可以使用YearMonth class 仅考虑年份和月份。 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 .导入java.time.temporal.ChronoUnitjava.time.YearMonth

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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