convert new zealand time to gmt in swift

To convert New Zealand time to GMT (Greenwich Mean Time) in Swift, we can use the DateFormatter and TimeZone classes provided by Apple. Here's an example implementation:

main.swift
let dateFormatter = DateFormatter() // create a DateFormatter object
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // set the date format
dateFormatter.timeZone = TimeZone(identifier: "Pacific/Auckland") // set the timezone to New Zealand
let date = dateFormatter.date(from: "2022-01-01 12:00:00")! // create a date object from a string

dateFormatter.timeZone = TimeZone(identifier: "GMT") // set the timezone to GMT
let dateString = dateFormatter.string(from: date) // format the date as a string in GMT timezone

print("New Zealand time: \(date) \nGMT time: \(dateString)")
580 chars
10 lines

In the above code, we first create a DateFormatter object and set the date format to match the input string ("yyyy-MM-dd HH:mm:ss"). We then set the timezone of the DateFormatter to New Zealand's timezone using the TimeZone(identifier:) constructor.

We next create a Date object by calling dateFormatter.date(from:) with our input string. This gives us a Date object representing the given New Zealand time.

To convert this to GMT time, we change the timezone of our DateFormatter object to "GMT". We then call dateFormatter.string(from:) with our Date object to get a string representation of the date in GMT timezone.

Lastly, we print out the original New Zealand time and the converted GMT time. Note that we force unwrap our Date object using the ! operator, as we assume that the input string is in the correct format and timezone. In practice, you should handle errors from parsing input strings more gracefully.

gistlibby LogSnag