The curious case of the 24-hour time format in Swift
Recently, I have found out how time formats on iOS devices can impact the ones inside a mobile app. Let's see how to make an application always display the 24-hour format regardless of your iPhone's or iPad's settings.
Time formats on iOS devices
As you probably know, in iOS you can choose between a 24-hour date format and 12-hour date format (A.M./P.M.). Depending on local tradition or habits, users usually choose one of these formats. They can change the format anytime they want via Settings (Settings > General > Date & Time).
But - which was something new for me - 24/12-hour formats have a big impact on date formats inside an app.
Default 24-hour time format
In one of the apps that I’m developing, a client wanted a 24-hour date format.It felt natural for him, because this format is popular in his region.
So, from API I’m getting a
String with a Rails format of the date. Then I need to parse this JSON endpoint into
Date(). More about handling Rails date formats in Swift can be found here.
Date() object needs to be changed into a
String that is displayed in app. I use a simple
DateFormatter() with parameters like these:
dateFormatter.dateFormat = "HH:mm"
Hour formats conflict
Soon afterwards, one of the users made a request claiming that the app had a bug. According to his claims, the dates were not displayed in a proper way.
After a quick investigation, we found out that he was using a 12-hour date format on his iPhone than the default 24-hours date format. And this little change impacted all the dates shown inside the app.
What I did
Of course, the simplest solution was to convince the user to change his Settings and use a 24-hour date format instead. But 'simplest' does not mean 'best'.
So I dove into the DateFormatter() to find out that there is a solution to force the app to display the hours in a certain way.
I wanted the app to always display the 24-hour date format, no matter if an iPhone uses a 12-hour or 24-hour date format. I needed to set HH and hide AM/PM markers. You can achieve this by using
customFormatter.setLocalizedDateFormatFromTemplate on DateFormatter():
Then you need to hide AM/PM markers:
customDateFormatter.amSymbol = ""
customDateFormatter.pmSymbol = ""
But this is not all yet. Sometimes the hour format can be forced by a particular region, so the best solution is to set locale:
customDateFormatter.locale = Locale(identifier: "en_US")
That’s all, folks! Now the date will be always dispalyed in the 24-hour format, no matter if a user changed their iPhone Settings or not.
Photo by Han Chau on Unsplash