在这个例子中,now和now + 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));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Now: 2020-07-31
Later: 2020-09-30
Months between now and later: 1
Run Code Online (Sandbox Code Playgroud)
我发现这一点只是因为我碰巧运行了一个单元测试,该测试的日期超出了预期......
查看 LocalDate.addMonths 的 javadoc:
此方法分三步将指定的金额添加到月份字段:
Run Code Online (Sandbox Code Playgroud)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 ......
获取两个日期之间的月数的正确方法是什么?
System.out.println(
"Months between now and later:" +
ChronoUnit.MONTHS.between(
YearMonth.from(now),
YearMonth.from(later)
)
);
Run Code Online (Sandbox Code Playgroud)
导入java.time.temporal.ChronoUnit和java.time.YearMonth.
| 归档时间: |
|
| 查看次数: |
65 次 |
| 最近记录: |