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.
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-31If 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-31The 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.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.