Why 'Y' Returns 2012 While 'y' Returns 2011 in SimpleDateFormat
SimpleDateFormat provides options to format dates using different patterns. Two common patterns, 'Y' and 'y', represent the week year and year, respectively. However, their behavior can be confusing.
Difference between 'Y' and 'y'
'Y': Represents the week year, which is aligned with the WEEK_OF_YEAR cycle. Week years may overlap calendar years, as explained in the Java documentation:
A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values.
Explanation of the Example
In the given example, 'y' returns 2011 because the current date is in the early days of January 2012. However, 'Y' returns 2012 because the week year (WEEK_OF_YEAR cycle) that includes January 2012 extends into the end of 2011. The documentation explains that the first days of a calendar year may belong to the previous week year.
Example Code
SimpleDateFormat sdf = new SimpleDateFormat("Y"); Date date = new Date(); // Current date // Print the week year (2012) System.out.println(sdf.format(date)); sdf = new SimpleDateFormat("y"); // Print the calendar year (2011) System.out.println(sdf.format(date));
The above is the detailed content of Why Does `SimpleDateFormat`'s 'Y' Return 2012 While 'y' Returns 2011?. For more information, please follow other related articles on the PHP Chinese website!