ThreeTen / threeten-extra

Provides additional date-time classes that complement those in JDK 8
http://www.threeten.org/threeten-extra/
BSD 3-Clause "New" or "Revised" License
387 stars 77 forks source link

Date difference of months calculated wrong (other than expected) #290

Closed afiller closed 10 months ago

afiller commented 10 months ago

My JUnit tests failed today at the last day of August because of the following problem:

They calculated the amout of months between now (2023-08-31) and in 3 months (2023-11-30) and came to the result of 2, which is in my opinion wrong:

2023-08-31 --> add 3 months (also Java comes to this result) --> 2023-11-30

...but Threeten-Extra means it's only 2:

        // Create dates for testing
        Date date1 = new Date(123, 7, 31, 12, 0, 0);
        Date date2 = new Date(123, 10, 30, 12, 0, 0);

        // Create ZoneDateTimes with the same zone
        ZonedDateTime dateTime1 = ZonedDateTime
                .from(date1.toInstant().atZone(ZoneId.systemDefault()));
        ZonedDateTime dateTime2 = ZonedDateTime
                .from(date2.toInstant().atZone(ZoneId.systemDefault()));

        // Show that dates are understood correctly
        System.err.println(date1);
        System.err.println(date2);
        // Calculate the months between
        System.err.println(Months.between(dateTime1, dateTime2).getAmount());

Output:

Thu Aug 31 12:00:00 CEST 2023
Thu Nov 30 12:00:00 CET 2023
2

It MAY come from the change from summer to winter time, but this should not have an effect on the months calculation.

Any ideas?

perceptron8 commented 10 months ago

This is correct. See https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#between-java.time.LocalDate-java.time.LocalDate-.

A month is considered if the end day-of-month is greater than or equal to the start day-of-month.

jodastephen commented 10 months ago

This is how java.time.* works, thus ThreeTen-Extra follows

afiller commented 10 months ago

Ok, thank you for clarifying.