I'm migrating my application from Joda-Time to the Java 8 java.time
.
One of the things I ran into is the printing of a week-based-year using a pattern in the DateTimeFormatter
.
NOTE: I have seen this question: Java Time's week-of-week-based-year pattern parsing with DateTimeFormatter
According to the documentation
y year-of-era year 2004; 04
Y week-based-year year 1996; 96
Yet when I try these two it seems the Y
is always returning the same as y
.
My testing code:
DateTimeFormatter yearF = DateTimeFormatter.ofPattern("yyyy").withZone(ZoneOffset.UTC);
DateTimeFormatter weekYearF = DateTimeFormatter.ofPattern("YYYY").withZone(ZoneOffset.UTC);
DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR_OF_ERA) .appendLiteral(" ") .append(yearF)
.appendLiteral(" -- ")
.appendValue(IsoFields.WEEK_BASED_YEAR) .appendLiteral(" ") .append(weekYearF)
.toFormatter()
.withZone(ZoneOffset.UTC);
System.out.println(dateTimeFormatter.toString());
ZonedDateTime dateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(946778645000L), ZoneOffset.UTC);
for (int i = 2000 ; i < 2020; i ++ ) {
System.out.println(dateTime.withYear(i).format(dateTimeFormatter));
}
The output:
Value(YearOfEra)' '(Value(YearOfEra,4,19,EXCEEDS_PAD))' -- 'Value(WeekBasedYear)' '(Localized(WeekBasedYear,4,19,EXCEEDS_PAD))
2000 2000 -- 1999 2000
2001 2001 -- 2001 2001
2002 2002 -- 2002 2002
2003 2003 -- 2003 2003
2004 2004 -- 2004 2004
2005 2005 -- 2004 2005
2006 2006 -- 2006 2006
2007 2007 -- 2007 2007
2008 2008 -- 2008 2008
2009 2009 -- 2009 2009
2010 2010 -- 2009 2010
2011 2011 -- 2010 2011
2012 2012 -- 2012 2012
2013 2013 -- 2013 2013
2014 2014 -- 2014 2014
2015 2015 -- 2015 2015
2016 2016 -- 2015 2016
2017 2017 -- 2017 2017
2018 2018 -- 2018 2018
2019 2019 -- 2019 2019
Looking at the years where it matters (like 2000, 2005, 2009 and 2016) the output of .appendValue(IsoFields.WEEK_BASED_YEAR)
and .ofPattern("YYYY")
are different.
In Java Time's week-of-week-based-year pattern parsing with DateTimeFormatter it is stated that this has to do with the localization (as can be clearly seen as a difference in the toString()
of the DateTimeFormatter
).
Now there are few things I do not understand/need:
So the 'week-based-year' varies with the Locale, fine. Yet what I do not understand that apparently in some Locales the week-base-year is always identical to the 'normal' year. Why is that?
Why hasn't the parsing of the
YYYY
been mapped to the ISO-8601 definition instead of the (terribly confusing!) Localized form.Where can I find proper documentation of this? The apparent 'official' documentation from Oracle is vague to say the least. Answer: I found much more extensive documentation with the DateTimeFormatterBuilder.