Understanding the Difference Between yyyy and YYYY in Java Date Formatting
The article explains a subtle Java date‑formatting bug where using the week‑based year pattern (YYYY) can incorrectly display the next calendar year for dates at year‑end, demonstrates the issue with sample code, and clarifies why yyyy should be used for ordinary year representation.
During a holiday test the author noticed an app showing the date 2020‑12‑30 instead of the expected 2019‑12‑30, which turned out to be caused by using the wrong date pattern in Java.
The following Java program creates a Calendar set to 2019‑08‑31, formats the date with SimpleDateFormat using both yyyy-MM-dd and YYYY-MM-dd , and prints the results:
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 yields:
2019-08-31 to yyyy-MM-dd: 2019-08-31
2019-08-31 to YYYY/MM/dd: 2019-08-31When 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-31The discrepancy arises because yyyy represents the calendar year (year‑of‑era), while YYYY denotes the week‑based year; if the week containing December 31 belongs to the next year, YYYY will output that next year.
This small but common pitfall can confuse users, so developers should prefer yyyy for ordinary year formatting to avoid such bugs.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.