Why Using YYYY‑MM‑dd Can Produce Wrong Years in Java Date Formatting

This article demonstrates how the week‑based year pattern "YYYY" in Java's SimpleDateFormat can incorrectly roll over the year for dates near year‑end, provides a reproducible unit test with code and output, and explains the underlying reason behind the discrepancy.

Programmer DD
Programmer DD
Programmer DD
Why Using YYYY‑MM‑dd Can Produce Wrong Years in Java Date Formatting

Reproducing the YYYY‑MM‑dd Issue

We create two SimpleDateFormat instances, one with the problematic pattern "YYYY-MM-dd" and another with the correct "yyyy-MM-dd", then format two dates: 2020‑12‑26 (Saturday) and 2020‑12‑27 (Sunday).

Test Code

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();
    // 2020-12-26 Saturday
    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()));
    System.out.println("========================");
    // 2020-12-27 Sunday
    c.add(Calendar.DATE, 1);
    System.out.println("YYYY-MM-dd = " + df1.format(c.getTime()));
    System.out.println("yyyy-MM-dd = " + df2.format(c.getTime()));
  }
}

Test Output

YYYY-MM-dd = 2020-12-26
yyyy-MM-dd = 2020-12-26
========================
YYYY-MM-dd = 2021-12-27
yyyy-MM-dd = 2020-12-27

Explanation

The pattern "YYYY" represents the week‑based year, which belongs to the year of the week that the date falls in. Because weeks start on Sunday and end on Saturday, a date that falls in the last week of December but belongs to the next week’s year (e.g., 2020‑12‑27) is formatted as 2021.

Using the lowercase "yyyy" formats the calendar year correctly, so the year remains 2020.

Check your code for this pattern to avoid unexpected year shifts.

SimpleDateFormatDate Formattingweek-based-year
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.