You Really Didn't Mean to Use Week Year

It’s that time of year again: PTO, and holidays, and… DateTime formatting edge case bugs.

Every year I see an escalated customer case come in somewhere, that Apex is doing date/times wrong, since somehow the last week of December in 2020 shows up with a year of 2021!

Apex delegates to the very, very commonly used Java SimpleDateFormat for the format string provided to DateTime.format(), and if you open the Java docs you’ll see two values for year next to each other: “Y” for “Week Year” and “y” for year.

Almost nobody knows what “week year” actually means, but Tom Scott summarizes it well, a semi-obscure ISO format that guarantees 52 full weeks per year, even if they don’t align with the calendar year. So, turns out, you really want to be using “y”, not “Y”.

The net result of using “Y”? You display December 30th and 31st (depending on Locale) as being in the next year.

Comments