Home > Java > javaTutorial > Why Does `SimpleDateFormat`'s 'Y' Return 2012 While 'y' Returns 2011?

Why Does `SimpleDateFormat`'s 'Y' Return 2012 While 'y' Returns 2011?

Mary-Kate Olsen
Release: 2024-12-28 02:52:13
Original
505 people have browsed it

Why Does `SimpleDateFormat`'s

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 calendar year, which typically ranges from 00 to 99. It resets to 00 at the beginning of each calendar year.
  • '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));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template