Why 'YYYY-MM-dd' Gives the Wrong Year in Java – The Week‑Based Year Pitfall
The article explains why using the pattern 'YYYY‑MM‑dd' with Java's SimpleDateFormat can produce an incorrect year for dates near the end of the year, demonstrates the issue with a unit test comparing it to the correct 'yyyy‑MM‑dd' pattern, and reveals that the problem stems from the week‑based year semantics of 'Y'.
The article discusses a common bug where using the pattern "YYYY-MM-dd" with Java's SimpleDateFormat yields an unexpected year for dates near the end of the year.
Test Setup
Two formatters are created: one with the problematic pattern "YYYY-MM-dd" and another with the correct pattern "yyyy-MM-dd". Both are used to format December 25, 2021 (Saturday) and December 26, 2021 (Sunday).
public class Tests {
@Test
public void test() throws Exception {
SimpleDateFormat df1 = new SimpleDateFormat("YYYY-MM-dd");
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2021);
c.set(Calendar.MONTH, 11);
// 2021-12-25 Saturday
c.set(Calendar.DATE, 25);
System.out.println("YYYY-MM-dd = " + df1.format(c.getTime()));
System.out.println("yyyy-MM-dd = " + df2.format(c.getTime()));
System.out.println("========================");
// 2021-12-26 Sunday
c.set(Calendar.DATE, 26);
System.out.println("YYYY-MM-dd = " + df1.format(c.getTime()));
System.out.println("yyyy-MM-dd = " + df2.format(c.getTime()));
}
}Running the test shows that for December 25 both patterns output 2021‑12‑25, but for December 26 the "YYYY-MM-dd" pattern outputs 2022‑12‑26 while the "yyyy-MM-dd" pattern correctly outputs 2021‑12‑26.
Reason
The symbol "Y" represents the week‑based year, which belongs to the year of the week that the date falls in. Since weeks start on Sunday, a Sunday that belongs to the first week of the next year causes the week‑based year to advance, so "YYYY" on 2021‑12‑26 yields 2022.
Using "yyyy" (calendar year) avoids this issue.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
