簡體   English   中英

如何獲取日期之間的月數?

[英]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:

此方法通過三個步驟將指定的金額添加到月份字段:

 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

例如,2007-03-31 加上一個月將導致無效日期 2007-04-31。 代替返回無效結果,而是選擇該月的最后一個有效日期 2007-04-30。

這意味着這是按預期工作的。 因此,無需求助於老式日期/時間 api ......

獲取兩個日期之間月數的正確方法是什么?

您可以使用YearMonth class 僅考慮年份和月份。 演示

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

導入java.time.temporal.ChronoUnitjava.time.YearMonth

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM