Post not yet marked as solved
Post marked as unsolved with 7 replies, 7,303 views
Using the new date formatting API available in iOS 15, I would like to respect the 12 vs 24 hour setting on a user-by-user basis.
With DateFormatter it can be done as follows, for example, to force a 24 hour time irrespective of the user locale.
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm" // or hh:mm for 12 h
However, I cannot figure out how to force the new date formatting API in iOS 15 to do the same thing, i.e. force displaying 12 vs 24 h.
I'm using a format style like this:
var formatStyle = dateTime
formatStyle.calendar = calendar
if let timeZone = timeZone {
formatStyle.timeZone = timeZone
}
return formatStyle
And applying it like this, for example, for a given Date instance:
date.formatted(formatStyle.hour(.defaultDigits(amPM: .abbreviated)))
However, this seems to always give a formatted string relevant to the locale, for example, it's always 12h for the US and always 24h for the UK. This is not the behaviour I really need though, and I'd like to allow each individual user to control what they see irrespective of the locale setting.
(Note that there is an in-app setting that allows the user to toggle between the 12 and 24 hour preference, which is the value I'd like to use to set the preference.)