Backend Development 4 min read

Understanding the Difference Between yyyy and YYYY in Java Date Formatting

This article explains how using 'YYYY' instead of 'yyyy' in Java's SimpleDateFormat can cause year miscalculations, especially around year-end weeks, demonstrates the issue with sample code, shows correct usage, and warns developers to avoid this subtle bug.

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

In the introductory section the author describes encountering a bug where an app displayed the date 2020‑12‑30 instead of the expected 2019‑12‑30, which was caused by using the wrong date pattern.

The author then presents a Java example that sets a calendar to 2019‑08‑31 and formats the date using both 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 this code produces the following output, showing that both patterns give the same result for this date:

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

When the date is changed to 2019‑12‑31, the output differs:

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

The discrepancy is due to the meaning of the pattern letters: y stands for the calendar year (year‑of‑era), while Y represents the week‑based year. If the week containing December 31 spans into the next year, Y will report the next year.

The article concludes by reminding developers to use the correct pattern ( yyyy ) for calendar years and to be aware of this subtle pitfall that can easily slip through testing.

JavaBackend Developmentprogrammingbugsimpledateformatdate formattingYear
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.