Backend Development 4 min read

Understanding the Difference Between yyyy and YYYY in Java Date Formatting

This article explains how using the uppercase YYYY pattern in Java's SimpleDateFormat can incorrectly shift dates to the next year for week‑based years, demonstrates the issue with sample code, and provides guidance to avoid this subtle bug in date handling.

Java Captain
Java Captain
Java Captain
Understanding the Difference Between yyyy and YYYY in Java Date Formatting

When using some apps, a bug caused the displayed date to jump from 2019‑12‑30 to 2020‑12‑30 due to a careless front‑end mistake, prompting the author to investigate the underlying Java date formatting issue.

Because the author has a background in Java, they present the problem to help developers avoid similar oversights.

Code Example

public class DateTest {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(2019, Calendar.AUGUST, 31);
        Date strDate = calendar.getTime();
        DateFormat formatUpperCase = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("2019-08-31 to yyyy-MM-dd: " + formatUpperCase.format(strDate));
        formatUpperCase = new SimpleDateFormat("YYYY-MM-dd");
        System.out.println("2019-08-31 to YYYY/MM/dd: " + formatUpperCase.format(strDate));
    }
}

Running this code produces:

2019-08-31 to yyyy-MM-dd: 2019-08-31
2019-08-31 to YYYY/MM/dd: 2019-08-31

If the date is changed to December 31:

2019-12-31 to yyyy-MM-dd: 2019-12-31
2019-12-31 to YYYY-MM-dd: 2020-12-31

The discrepancy arises because yyyy represents the calendar year, while YYYY denotes the week‑based year; if the week spans the new year, YYYY advances to the next year. This subtle difference can confuse users, so developers should consult the documentation.

The article includes an explanatory image clarifying that y is the year‑of‑era and Y is the week‑based year, illustrating why December 31, 2019 falls into week‑based year 2020.

Finally, the author wishes readers bug‑free coding and encourages appreciation for the post.

Javabackend developmentyyyy vs YYYYbug preventiondate formatting
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login 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.