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”.
If you're using YYYY instead of yyyy in your java/apex date formats: https://t.co/rC1ocHU1tQ— Chris Peterson (@ca_peterson) December 30, 2020
The net result of using “Y”? You display December 30th and 31st (depending on Locale) as being in the next year.
every year 😠 pic.twitter.com/2ADptN7WM3— new baby no sleep just vibes (@isEqualToDan) December 22, 2020