Post

Replies

Boosts

Views

Activity

Set 12 vs 24 hour with the new date formatting API in iOS 15
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.)
7
0
9.4k
Mar ’22
Set time zones with the new date formatting API in iOS 15
I would like to update some code that uses DateFormatter, for example, code like this: let date = Date() let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .short formatter.timeZone = TimeZone(identifier: "Europe/London") formatter.string(from: date) With the new date formatting API available in iOS 15, date formatting can be achieved by calling the formatted() method on the date directly, without explicitly requiring a DateFormatter instance, for example: date.formatted(.dateTime.year().month().day().hour().minute()) However, using this new API, I cannot find any way to set the time zone, i.e., the equivalent of the line formatter.timeZone = TimeZone(identifier: "Europe/London"). I'm aware that time zone can be used to format the output, for example date.formatted(.dateTime.timeZone()), but this does not allow one to actually set the time zone. Does anyone know if it is possible?
4
0
7.1k
Feb ’22