从LocalDate添加和减去Period不会产生相同的日期 [英] Adding and subtracting Period from LocalDate doesn't produce the same date

查看:209
本文介绍了从LocalDate添加和减去Period不会产生相同的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用java 8 LocalDate和Period类来添加和删除年,月和日。为什么在某些情况下如果添加Period到date并删除相同的句点java 8会返回另一个日期?

i use java 8 LocalDate and Period classes to add and remove years, months and days. Why in some cases if add Period to date and remove the same period java 8 return another date?

    LocalDate date = LocalDate.of(2023, 1, 30);
    Period period = Period.of(6, 1, 1);
    System.out.println(date.plus(period).minus(period));

为什么结果是2023-01-31而不是2023-01-30

why the result is 2023-01-31 not 2023-01-30

推荐答案


为什么在某些情况下如果添加Period to date并删除sane period java 8会返回另一个日期?

Why in some cases if add Period to date and remove the sane period java 8 return another date?

因为这就是日历运算的工作原理 - 几个月的长度不均匀,至少可以说这很麻烦。

Because that's how calendrical arithmetic works - months are uneven lengths, and it makes things tricky to say the least.

你将六年,一个月,一天添加到2023年1月30日。你期望 的结果是什么?可能存在多种不同的选项......从逻辑上讲,它听起来像是指2029年2月31日,它不存在......所以API将它推到2029年3月1日。

You're adding "six years, one month, one day" to January 30th 2023. What do you expect the result of that to be? There are potentially multiple different options... logically it sounds like you mean "February 31st 2029" which doesn't exist... so the API rolls it over to March 1st 2029.

现在减去六年,从2029年3月1日开始的一个月零一天也有些含糊不清,但是在2023年1月31日这样做是合理的 - 如果你减去6年到3月份2023年1月,然后1个月到2023年2月1日,然后1天你到1月31日。

Now subtracting six years, one month and one day from March 1st 2029 is also somewhat ambiguous, but it sounds reasonable to make it January 31st 2023 - if you subtract 6 years to get to March 1st 2023, then 1 month to get to February 1st 2023, then 1 day you get to January 31st.

从根本上说:不要指望日历算术表现得像常规数学。它只是不起作用。

Fundamentally: don't expect calendrical arithmetic to behave like regular maths. It just doesn't work that way.

这篇关于从LocalDate添加和减去Period不会产生相同的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆