问题
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?
回答1:
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).
回答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
回答3:
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
来源:https://stackoverflow.com/questions/59343748/datetimeformatter-adding-a-year-to-date-after-formatting