Bad practice: using "YYYY" to format a Date


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


Can you guess what’s wrong with this code?

We create a DateFormatter and then we set the dateFormat it will use to format dates into strings.

At first glance, everything seems fine.

But there’s actually a big problem with the dateFormat!

You see, we’re using "YYYY" to specify that we want the year of the date to be displayed over 4 digits.

But using "YYYY" is actually a mistake!

If we want to display the year of the date, we need to use "yyyy".

So what does "YYYY" actually do?

"YYYY" will display the year in which the week had begun.

In many situations, both will be the same.

However, for dates that take place at the beginning of a new year, it will often result in a different year being displayed!

If we take the example of January 1st, 2023, using "YYYY" will display the year 2022 because it was a Sunday and so the week it’s part of had indeed begun in 2022.

This kind of formatting does make sense in some very rare situations, where you need each year to be made of exactly 52 undivided weeks.

But in most cases, this is definitely not what you want and so you definitely want to use "yyyy" to format the year of a date.

What’s really tricky here is that if you make the mistake to of using "YYYY", it’s very easy for the issue to go unnoticed for several months, until you reach the beginning of a new year!

That’s all for this article, I hope you’ve enjoyed discovering this tricky pitfall of date formatting!

Here’s the code if you want to experiment with it:

import Foundation

let date = dateOf_01_01_2023()

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "dd/MM/YYYY"
dateFormatter.string(from: date) // 01/01/2022

dateFormatter.dateFormat = "dd/MM/yyyy"
dateFormatter.string(from: date) // 01/01/2023
Previous
Previous

How to easily debug your network code 🛰️

Next
Next

How to get started with The Composable Architecture 📱