【问题标题】:Java LocalDate getting two different results when calling plusDays plusMonths and plusYearsJava LocalDate 在调用 plusDays plusMonths 和 plusYears 时得到两个不同的结果
【发布时间】:2021-04-26 08:11:27
【问题描述】:
大家好,我有这样的代码
public static void main(String[] args) {
System.out.println(LocalDate.now().plusYears(1).plusMonths(6).plusDays(5));
System.out.println(LocalDate.now().plusDays(5).plusMonths(6).plusYears(1));
}
我得到两个不同的结果
2022-10-31
2022-11-01
有人可以解释为什么吗?谢谢
【问题讨论】:
标签:
java
java-8
java-time
localdate
【解决方案1】:
因为plusDays 与给定月份相关...
假设您在 9 月 26 日,加上 5 天将得到 10 月 1 日。
如果您在 8 月 26 日,则将您带到 8 月 31 日。
日期的算术不是数字的算术...一个月就是一个月,并且不能转换为天数。
请参阅有关plusMonths的文档,例如:
public LocalDate plusMonths(long monthsToAdd)
...
例如,2007-03-31 加上一个月将导致无效日期 2007-04-31。代替返回无效结果,而是选择该月的最后一个有效日期 2007-04-30。
这是通常的预期,将日期添加 1 个月将导致您到达下个月的日期。但是几天不一样,你真的要移动几天。
【解决方案2】:
尝试printing the intermediate results 帮助直观地了解操作如何应用于不同顺序的日期:
// Fix the date, so this is reproducible after today!
LocalDate now = LocalDate.of(2021, 4, 26);
System.out.println("First:");
System.out.println(now);
System.out.println(now.plusYears(1));
System.out.println(now.plusYears(1).plusMonths(6));
System.out.println(now.plusYears(1).plusMonths(6).plusDays(5));
System.out.println("Second:");
System.out.println(now);
System.out.println(now.plusDays(5));
System.out.println(now.plusDays(5).plusMonths(6));
System.out.println(now.plusDays(5).plusMonths(6).plusYears(1));
输出:
First:
2021-04-26
2022-04-26
2022-10-26
2022-10-31
Second:
2021-04-26
2021-05-01
2021-11-01
2022-11-01
不同是因为四月和十月的长度不同:从今天起的 5 天,你在五月;距离 10 月 26 日还有 5 天,你还在 10 月。
【解决方案3】:
4 月有 30 天,10 月 31 日。如果您先添加天数,则会进入下个月,如果您先添加月份,则不会:
2021-04-26 + 1Year -> 2022-04-26 + 6Month -> 2022-10-26 + 5Days -> 2022-10-31
2021-04-26 + 5Days -> 2021-05-01 + 6Month -> 2021-11-01 + 1Year -> 2022-11-01