javatimelocalizationutcdatetimeformatter

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


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.


Solution

  • 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.