Why does Java's java.time.format.DateTimeFormatter#format(LocalDateTime) add a year?

╄→尐↘猪︶ㄣ 提交于 2019-12-04 02:27:40

问题


This is the code:

LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(1451438792953L), ZoneId.of("UTC"));
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("YYYY-MM-dd'T'HH:mm:ss.SSS'Z'");
String output = dateTimeFormatter.format(localDateTime);

This is the value of localDateTime:

2015-12-30T01:26:32.953

This is the value of output:

2016-12-30T01:26:32.953Z

Why does it add a year?

In java.time.temporal.WeekFields there are a couple of methods with a newYearWeek which increment the year by 1 on occasion. Why?

This is a strange bug.


回答1:


From Wikipedia:

[YYYY] indicates the ISO week-numbering year which is slightly different from the traditional Gregorian calendar year (see below).

  1. YYYY is an ISO-8601 style representation of the year.
  2. yyyy is the Gregorian year-of-era representation.

Since the the calculation of the two can be different by +1 or -1, hence the formatting. More useful info at YEAR_OF_ERA, YEAR, and weekBasedYear.



来源:https://stackoverflow.com/questions/34521733/why-does-javas-java-time-format-datetimeformatterformatlocaldatetime-add-a-y

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!