I wonder why 'Y' returns 2012 while 'y' returns 2011 in SimpleDateFormat
:
System.out.println(new SimpleDateFormat("Y").format(new Date())); // prints 2012
System.out.println(new SimpleDateFormat("y").format(new Date())); // prints 2011
Can any one explain why?
Format
Y
to get week year if calendar support week year. (getCalendar().isWeekDateSupported()
)I learned the hard way the JSTL tag library
format:date
withshort
as the requested format uses YYYY under the covers. Which can indeed roll the printed date ahead a year.week year and year. From javadoc
Here's a Java 8 update with some code, as GregorianCalendar will probably be deprecated or removed from future JDK versions.
The new code is handled in the
WeekFields
class, and specifically for the lower casey
/ upper caseY
with theweekBasedYear()
field accessor.The setup of this
WeekFields
instance depends on the locale and may have different settings depending on it, US and European countries like France may have a different day as start of the week.For example the
DateFormatterBuilder
of Java 8, instantiate the parser with the locale, and use this locale for theY
symbol :Here's some example
And in regard of the locale and the upper case
Y
, you can either play with the command line option-Duser.language=
(fr
,en
,es
, etc.), or force the locale at invocation time :