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?
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With