Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTimeFormatter adding a year to date after formatting [duplicate]

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?

like image 514
jobin Avatar asked Dec 10 '22 01:12

jobin


2 Answers

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).

like image 108
Jon Skeet Avatar answered Dec 22 '22 00:12

Jon Skeet


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
like image 39
Razib Avatar answered Dec 21 '22 22:12

Razib