Edge case date issues in APEX

Chris Peterson tweeted a good reminder this morning that the subtle difference between YYYY and yyyy in the Java date format can lead to unexpected date bugs in your APEX code around this time of year.

For most of the year, the output of Datetime.format('MM/dd/YYYY') and Datetime.format('MM/dd/yyyy') will appear to be interchangeable and all your tests will seem to pass.

The java date format documentation doesn't make it particularly clear that the YYYY year format is using the ISO week date calendar while the yyyy format uses the Gregorian calendar.

These two calendars will appear to align throughout the year and the difference in their outputs will only be noticeable a few days before and/or a few days after the end of a year.

For example, today is December 31, 2020 according to the Gregorian calendar, but if using the MM/dd/YYYY date format, the output will be 12/31/2021.

Try it for yourself...

Datetime calendarDay = Datetime.newInstance(2020,12,31);

System.debug('Gregorian Calendar Date: ' + calendarDay.format('MM/dd/yyyy'));
System.debug('ISO Weeks Calendar Year Format: ' + calendarDay.format('MM/dd/YYYY'));

You'll only receive email when Scott McClung publishes a new post

More fromĀ Scott McClung