LocalDate 格式化程序错误?

LocalDate formatter bug?

我在 12 月 30 日和 31 日的 LocalDate 上使用 Java 的 DateTimeFormatter 时发现了奇怪的行为。

LocalDate date1 = LocalDate.of(2019, Month.DECEMBER, 30);
System.out.println("date1:           " + date1);
System.out.println("converted date1: " + DateTimeFormatter.ofPattern("YYYY-MM-dd").format(date1));

LocalDate date2 = LocalDate.of(2019, Month.JANUARY, 30);
System.out.println("date2:           " + date2);
System.out.println("converted date2: " + DateTimeFormatter.ofPattern("YYYY-MM-dd").format(date2));

输出:

date1:           2019-12-30
converted date1: 2020-12-30
date2:           2019-01-30
converted date2: 2019-01-30

第一个日期(12 月 30 日)转换为下一年,第二个日期(1 月 30 日)转换为正确的年份。

我是不是遗漏了什么,或者这是一个错误?

Y 表示 "year of week-based year"。它与 y 不同,后者根据 docs 表示 "year of era"。

This post解释Y的区别和用途:

A week year is a year where all the weeks in the year are whole weeks. This is specified by some standard (which I don't remember at the moment). Basically, this guarantees that a program working on a week's data will not transition between years. Unfortunately, this also means that the beginning of the year may not start on the first of January. What year a particular day belongs in depends on these rules, and of course, there are days where the year and the week year are different.

在您的示例中,2019 年 12 月 30 日是星期一,19 年 12 月 31 日是星期二,20 年 1 月 1 日是星期三,因此这三天的 "year of week-based year" 是 2020 年。

将 'Y' 更改为 'y'(大写变为小写)'Y' 是基于周的年份,因为 2019 年 12 月 30 日这一周的大部分时间都属于 2020 年是 2020 年。而小写 'y' 是您的常规年份。有关详细信息,请参阅 DateTimeFormatter 的 JavaDoc