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?
To do this, change the timeZone
property on the style itself. For example, this code:
import Foundation
func main() {
let d = Date()
var f = Date.FormatStyle.dateTime
print(d.formatted(f))
f.timeZone = TimeZone(identifier: "Australia/Perth")!
print(d.formatted(f))
}
main()
prints:
09/02/2022, 10:04
09/02/2022, 18:04
[I’m on GMT so I can’t use your Europe/London
example (-: ]
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"