DateTimeFormatter格式化后添加年份到日期 [英] DateTimeFormatter adding a year to date after formatting
问题描述
我正在尝试将格式为 2019-12-30
的日期转换为格式为 30-12-2019 $的日期c $ c>,为此,我想到了使用
DateTimeFormatter
,为此,我有以下代码:
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
而不是预期 30-12-2019
。如果日期设置为 2019-11-30
,则正确返回 30-11-2019
。我做错了非常严重的事,但我无法弄清楚到底是什么。有人可以帮忙吗?
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?
推荐答案
来自 DateTimeFormatter
文档:,指示符号,含义和示例:
From the DateTimeFormatter
documentation:, indicating the symbol, meaning and examples:
是基于1996年的Y周; 96
Y week-based-year year 1996; 96
因此,您要格式化基于星期的年份,而不是常规年份。 2019年12月30日属于2020年的第一周,因此您的输出。
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.
使用 yyyy
(时代)或 uuuu
(年),而不是 YYYY
,您将得到2019年。
Use yyyy
(year-of-era) or uuuu
(year) instead of YYYY
and you'll get 2019 instead.
基本上, YYYY
通常应与 w
一起使用(一周中的一周-based-year)和 E
(星期几)。
Basically, YYYY
should usually be used with w
(week-of-week-based-year) and E
(day-of-week).
这篇关于DateTimeFormatter格式化后添加年份到日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!