Adding and subtracting Period from LocalDate doesn't produce the same date

与世无争的帅哥 提交于 2019-11-28 01:47:35

问题


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));

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


回答1:


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.

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.

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.



来源:https://stackoverflow.com/questions/41945704/adding-and-subtracting-period-from-localdate-doesnt-produce-the-same-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!