4

I am trying to convert a date of the format 2019-12-30 to a date with format 30-12-2019 and for this I thought of using DateTimeFormatter and I have the following code for this:

LocalDate date = LocalDate.parse("2019-12-30");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-YYYY");
System.out.println(formatter.format(date));

However, to my surprise, this returns an output:

30-12-2020

instead of the expected 30-12-2019. If the date is set to 2019-11-30, it correctly returns 30-11-2019. I am doing something terribly wrong but I am not able to figure out what exactly. Can someone please help?

jobin
  • 2,600
  • 7
  • 32
  • 59

3 Answers3

10

From the DateTimeFormatter documentation:, indicating the symbol, meaning and examples:

Y week-based-year year 1996; 96

So you're formatting the week-based-year, not the regular year. December 30th 2019 belongs to the first week of 2020, hence your output.

Use yyyy (year-of-era) or uuuu (year) instead of YYYY and you'll get 2019 instead.

Basically, YYYY should usually be used with w (week-of-week-based-year) and E (day-of-week).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Use "dd-MM-yyyy" instead of "dd-MM-YYYY" Try the following code snippet to get expected result -

LocalDate date = LocalDate.parse("2019-12-30");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
System.out.println("date " + formatter.format(date)); // date 30-12-2019
Razib
  • 10,965
  • 11
  • 53
  • 80
  • 1
    You had an explanation as to why I should use `yyyy` before, that answer is much better. Can you please edit and add the explanation back? – jobin Dec 15 '19 at 13:01
1

You are using DateTimeFormatter.ofPattern("dd-MM-YYYY"); and notice that Y stands for week-based-year, which you probably don't want. Perhaps you want yout pattern to be "dd-MM-uuuu". For more information on patterns, refer to the official Oracle documentation: Patterns for Formatting and Parsing

Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52