Why Does Using 'YYYY' in Java Date Formatting Show the Wrong Year?
A Java date‑formatting bug occurs when the week‑based year pattern 'YYYY' is used instead of the calendar year 'yyyy', causing dates near year‑end to display the next year, and this article explains the cause, demonstrates it with code, and shows how to avoid it.
When using an app I noticed a bug where a date displayed as 2020‑12‑30 instead of the intended 2019‑12‑30, caused by using the wrong date pattern in Java.
Below is a simple Java example that formats a Calendar date using both yyyy and YYYY patterns.
public class DateTest {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(2019, Calendar.AUGUST, 31);
Date date = calendar.getTime();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("2019-08-31 to yyyy-MM-dd: " + fmt.format(date));
fmt = new SimpleDateFormat("YYYY-MM-dd");
System.out.println("2019-08-31 to YYYY/MM/dd: " + fmt.format(date));
calendar.set(2019, Calendar.DECEMBER, 31);
date = calendar.getTime();
fmt = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("2019-12-31 to yyyy-MM-dd: " + fmt.format(date));
fmt = new SimpleDateFormat("YYYY-MM-dd");
System.out.println("2019-12-31 to YYYY-MM-dd: " + fmt.format(date));
}
}The output shows that for dates in the last week of the year, YYYY may roll over to the next year because it represents the week‑based year, while yyyy represents the calendar year.
Understanding this subtle difference prevents bugs where users see an unexpected year, especially around New Year's week.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack 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.
