Backend Development 4 min read

Understanding the Difference Between yyyy and YYYY in Java Date Formatting

This article explains the subtle difference between 'yyyy' and 'YYYY' in Java's SimpleDateFormat, demonstrates how using the wrong pattern can cause year miscalculations—especially on December 31st—and provides code examples and a clear explanation to help developers avoid this common bug.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Understanding the Difference Between yyyy and YYYY in Java Date Formatting

Hello everyone, I'm Architecture Jun, an architect who writes code and poetry.

Preface: While traveling during the New Year holiday, I noticed an app displaying the wrong year—showing 2020-12-30 instead of 2019-12-30—due to a front‑end oversight.

Because such mistakes can mislead users, I share the issue I encountered when I previously studied Java.

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 prints:

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 problem appears because 'y' denotes year‑of‑era, while 'Y' denotes week‑based‑year; when the week spans the new year, 'Y' can belong to the next year.

Although this is a small detail, many developers fall into this pitfall; record it and share if you find it useful. I wish you bug‑free coding.

backendJavabugsimpledateformatdate formatting
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

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.