2

When using DateTimeFormatter of format "yyMMdd", strange things happen... LocaleDate.of(0,1,5) is formatted to "010105", but "000105" is correctly parsed to LocalDate.of(2015, 1, 5). Why is that??

For testing:

@Test
public void testYear2000() {
    LocalDate localDate = LocalDate.of(0, 1, 5);
    String format = DateTimeFormatter.ofPattern("yyMMdd").format(localDate);

    assertThat(format, is("000105")); // fail! it is "010105"

    LocalDate parse = LocalDate.parse("000105", DateTimeFormatter.ofPattern("yyMMdd"));

    assertThat(parse, is(LocalDate.of(2000, 1, 5))); //pass
}
Hengrui Jiang
  • 861
  • 1
  • 10
  • 23

2 Answers2

4

I add the supplementary explanation for the correct answer of @Lachezar Balev. Printing the year 0 (more than two thousand years ago) by the pattern yy means: Use the two-digit-form of year-of-era equivalent to proleptic gregorian year 0 which is 1 BCE. Therefore you see the year 1 in formatted output 010105.

If you had used the pattern uuMMdd (u=proleptic gregorian year) then the output would indeed match your expectation 000105 but is still fundementally wrong due to wrong input.

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
3

Your confusion comes from the fact that here:

LocalDate.of(0, 1, 5);

you have specified year zero, which is millenniums before the year of 2000:

LocalDate.of(2000, 1, 5);

The last will output 000105.

Update: @Meno Hochschild added further explanations and I would also link this nice question for reference.

Community
  • 1
  • 1
Lachezar Balev
  • 11,498
  • 9
  • 49
  • 72