gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:19:18 36 4
gpt4 key购买 nike

在此示例中,nownow + 2 个月 之间的差异不等于 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 threesteps:

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 invaliddate 2007-04-31. Instead of returning an invalid result, the lastvalid day of the month, 2007-04-30, is selected instead.

这意味着这正在按预期工作。因此,无需求助于复古日期/时间 API...

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

最佳答案

您可以使用YearMonth类只考虑年和月。 Demo

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

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

关于java - 如何获取日期之间的月份数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63257296/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com