Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...