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.
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-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-31Developers should use y for calendar dates to avoid such bugs.
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!
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.