convert gmt to new zealand time in swift

To convert a date from GMT to New Zealand time in Swift, you can use the following code:

main.swift
let gmtDate = Date() // replace with your GMT date object

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = TimeZone(identifier: "GMT")

// get the equivalent date and time in New Zealand time zone
formatter.timeZone = TimeZone(identifier: "Pacific/Auckland")
let nzDateString = formatter.string(from: gmtDate)

// convert the string back to a Date object
let nzDate = formatter.date(from: nzDateString)
453 chars
13 lines

In this code, we first create a Date object representing the current date in GMT. We then create a date formatter and set its time zone to GMT. We use this formatter to convert the gmtDate object to a string with the format yyyy-MM-dd HH:mm:ss.

Next, we change the time zone of the formatter to New Zealand (Pacific/Auckland), and use it to convert the string to a new string representing the same date and time in New Zealand time.

Finally, we pass the resulting string back to the formatter to convert it to a Date object, which we store in the nzDate variable.

gistlibby LogSnag