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.swift580 chars10 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