Formatting dates in the user’s locale using DateFormatter in SwiftPublished on: October 15, 2020
Working with dates is hard, there is no doubt about that. And formatting dates properly for every user of your app is no easier (if you want to do everything manually). Luckily, the system can help us.
Free In-App Messaging SDK & UI Kits for iOS/Swift
Stream's Chat SDK helps you build beautiful chat applications with as little code as possible. With our SDKs, you can bring high-quality chat experiences to all of your end-users. SDKs are available for SwiftUI.
Try for free
This sponsored message helps keep the content on this site free. Please check out this sponsor as it directly supports me and this site.
For example, in the US one would write "October 15" while in The Netherlands we write 15 oktober.
Note that the order of the date and the month is different, the spelling of the month is different and the capitalization is different too.
The DateFormatter in iOS will handle a lot of this for you. For example, if you'd use the following code on a device that uses
nl as its locale you would see the output that I added to this snippet as a comment:
let now = Date() let formatter = DateFormatter() formatter.dateFormat = "dd MMMM" formatter.string(from: now) // 15 oktober
The output of this code is spot on. Exactly what we need and it matches the specified date format perfectly. If you'd run the same code on a device that uses
en_us as its locale the output would be 15 October.
The date formatter got the spelling and capitalization right but the date and month are in the wrong order.
You can fix this by using
setLocalizedDateFormatFromTemplate on your date formatter instead of assigning its
dateFormat directly. Let's look at an example that runs on a device with
nl as its locale again:
let now = Date() let formatter = DateFormatter() formatter.setLocalizedDateFormatFromTemplate("dd MMMM") formatter.string(from: now) // 15 oktober
That still works, perfect. If you'd run this code on an
en_us device the output would be October 15. Exactly what we need.
If you want to play around with
setLocalizedDateFormatFromTemplate in a Playground you can give it a go with the following code that uses a date formatter in different locales:
import Foundation let now = Date() let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_us") formatter.setLocalizedDateFormatFromTemplate("dd MMMM") formatter.string(from: now) // October 15 formatter.locale = Locale(identifier: "nl") formatter.setLocalizedDateFormatFromTemplate("dd MMMM") formatter.string(from: now) // 15 oktober
If you have questions about this Quick Tip, or if you want to reach out to me for other reasons then don't hesitate to send me a message on Twitter.
It's a good thing that Swift and Foundation can handle these kinds of