Member-only story
dateFormat’s One Big Mistake
Your location. Your timeZone.
2 min readMay 4, 2020
This article will cover the big issue with dateFormatter, and how you might overcome it. Be aware that I’ve coded everything within this article in Swift using Playgrounds.
No Problem: Creating a Date
let now: Date = Date()
No obvious problem: Displaying a date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd"
let dateString = dateFormatter.string(from: now)
print (dateString)
Now since today is Sunday 3rd May 2020, on my machine I print to the console:
2020-56-03
Have you seen the problem in what I’ve written above?
The problem
dateFormatter is not locale aware, and this means that the user can potentially change this (like their region) from their device.
Solution number one:
Force the locale to be the region you want (for example, if you wear a cowboy hat the US).
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateFormat = "yyyy-mm-dd"
dateFormatter.timeZone = TimeZone(identifier: "Europe/London")
let dateString = dateFormatter.string(from…