Fundamentals 4 min read

Understanding the Difference Between yyyy and YYYY in Java SimpleDateFormat

The article explains that in Java's SimpleDateFormat the lowercase y pattern (year‑of‑era) should be used for calendar dates, because the uppercase Y pattern represents a week‑based year which can incorrectly roll over to the next year near year‑end, causing bugs.

Java Tech Enthusiast
Java Tech Enthusiast
Java Tech Enthusiast
Understanding the Difference Between yyyy and YYYY in Java SimpleDateFormat

The article discusses a common Java date formatting bug where using YYYY-MM-dd instead of yyyy-MM-dd can cause year rollover issues near year-end.

It explains that y stands for year-of-era, while Y stands for week-based year, which may belong to the next year if the week crosses a year boundary.

Example code:

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));
    }
}

Output for 2019-08-31:

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

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

Developers should use y for calendar dates to avoid such bugs.

Javaprogrammingbugdateformatsimpledateformatyyyy vs YYYY
Java Tech Enthusiast
Written by

Java Tech Enthusiast

Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!

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.