Sample test
@Test
public void should_be_equals(){
LocalDate now = new LocalDate(2015,01,29);
assertThat(now.plusMonths(1).plusMonths(1)).isEqualTo(now.plusMonths(2));
}
The strange result:
org.junit.ComparisonFailure:
Expected :2015-03-29
Actual :2015-03-28
Why this differs?
If you would add one month to 2015/01/29
, you would get 2015/02/29
- since 2015 isn't a leap year, that's not a valid date, so Joda chooses 2015/02/28
, as documented:
The addition may change the year, but the day-of-month is normally unchanged. If adding months makes the day-of-month invalid, it is adjusted to the last valid day in the month.
And another month added to 2015/02/28
will result in the actual date 2015/03/28
.
The problem with the missing 29th of February doesn't appear when adding two months, because Joda never gets an invalid date.
The same does apply to, for instance, new LocalDate(2015, 03, 31).plusMonths(2)
versus new LocalDate(2015, 03, 31).plusMonths(1).plusMonths(1)
- I guess, this is more common than leap years.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With