Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JodaTime: plusMonths(1) two times differ from plusMonths(2)

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?

like image 449
MariuszS Avatar asked Jan 29 '15 12:01

MariuszS


1 Answers

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.

like image 60
stuXnet Avatar answered Oct 22 '22 12:10

stuXnet