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

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

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow