Backend Development 4 min read

Understanding the Difference Between yyyy and YYYY in Java Date Formatting

The article explains how using the week‑based year pattern (YYYY) instead of the calendar year pattern (yyyy) in Java's SimpleDateFormat can cause dates like 2019‑12‑31 to be displayed as 2020‑12‑31, illustrating the issue with code examples and a clear explanation of the underlying rules.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Understanding the Difference Between yyyy and YYYY in Java Date Formatting

During the New Year holiday the author noticed a bug in an app where the displayed date jumped from 2019‑12‑31 to 2020‑12‑31, caused by using the wrong date pattern in Java.

The following Java program demonstrates the issue by formatting the same Calendar date with yyyy-MM-dd and YYYY-MM-dd patterns.

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 the program for August 31 prints the same result for both patterns, but changing the date to December 31 produces different output:

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

The reason is that y represents the calendar year (year‑of‑era), while Y represents the week‑based year; if the week containing the date belongs to the next year, Y will output that next year.

Understanding this subtle difference helps developers avoid confusing date bugs in Java applications.

backendjavasimpledateformatyyyy vs YYYYcalendardate formatting
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

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.