Formatting Years as Strings
In date formatting, yyyy
is not the same as YYYY
.
Apple’s Date Formatting document describes this:
A common mistake is to use
YYYY
.yyyy
specifies the calendar year whereasYYYY
specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases,yyyy
andYYYY
yield the same number, however they may be different. Typically you should use the calendar year.
You can test Swift’s DateFormatter with 2016-01-01: YYYY
will tell you it’s 2015, not 2016, because it’s a Friday, at the end of 2015 by the year-week calendar logic.
If you’re working with date formatters, it’s a good idea to include 2016-01-01 in your unit tests, just to make sure you format the date as you expect.
Published on 27 April 2024