1

I found strange behaviour when using Java's DateTimeFormatter on LocalDate for 30th and 31st of December.

LocalDate date1 = LocalDate.of(2019, Month.DECEMBER, 30);
System.out.println("date1:           " + date1);
System.out.println("converted date1: " + DateTimeFormatter.ofPattern("YYYY-MM-dd").format(date1));

LocalDate date2 = LocalDate.of(2019, Month.JANUARY, 30);
System.out.println("date2:           " + date2);
System.out.println("converted date2: " + DateTimeFormatter.ofPattern("YYYY-MM-dd").format(date2));

Output:

date1:           2019-12-30
converted date1: 2020-12-30
date2:           2019-01-30
converted date2: 2019-01-30

The first date (December 30) is converted with the next year, the second date (January 30) is converted with the correct year.

Am I missing something out, or is it a bug?

  • 4
    You probably wanted `yyyy` instead of `YYYY`. You need to be careful with those patterns, they're not just random letters. – Kayaman Jan 22 '20 at 13:43
  • A handy tip to keep in mind: https://blog.codinghorror.com/the-first-rule-of-programming-its-always-your-fault/ – Klitos Kyriacou Jan 22 '20 at 14:05

2 Answers2

4

Y means "year of week-based year". It's not the same as y which means "year of era" as per docs.

This post explains the difference and purpose of Y:

A week year is a year where all the weeks in the year are whole weeks. This is specified by some standard (which I don't remember at the moment). Basically, this guarantees that a program working on a week's data will not transition between years. Unfortunately, this also means that the beginning of the year may not start on the first of January. What year a particular day belongs in depends on these rules, and of course, there are days where the year and the week year are different.

In your example 30st Dec '19 was a Monday, 31st Dec '19 was a Tuesday and 1st Jan '20 was Wednesday so "year of week-based year" for this three days is 2020.

Karol Dowbecki
  • 38,744
  • 9
  • 58
  • 89
1

Change 'Y' to 'y' (Capital case to lower case) 'Y' is week based year and since most of the week of Dec-30, 2019 falls into 2020 the year is 2020. while lower case 'y' is your regular year. See JavaDoc for DateTimeFormatter for details

Michael Gantman
  • 4,318
  • 1
  • 12
  • 31