I got timezone format like this GMT+5:30.
TimeZone.current.abbreviation(), this will return string value like: //GMT+5:30
But I need to convert the above format to Asia/Kolkata
How to solve this issue?
I got timezone format like this GMT+5:30.
TimeZone.current.abbreviation(), this will return string value like: //GMT+5:30
But I need to convert the above format to Asia/Kolkata
How to solve this issue?
Instead of calling:
TimeZone.current.abbreviation()
call:
TimeZone.current.identifier
In your case you will get Asia/Kolkata
instead of GMT+5:30
.
But let's assume you only have a string with a timezone abbreviation such as "GMT+5:30"
. You can't easily convert that to a specific timezone identifier because there can be more than one timezone at a given time offset.
Here's a little function that creates a timezone from the abbreviation string and then finds all matching timezone identifiers that have the same offset.
func matchingTimeZones(abbreviation: String) -> [TimeZone]? {
if let tz = TimeZone(abbreviation: tzstr) {
return TimeZone.knownTimeZoneIdentifiers.compactMap { TimeZone(identifier: $0) }.filter { $0.secondsFromGMT() == tz.secondsFromGMT() }
} else {
return nil
}
}
You can get the matching list for "GMT+5:30"
with:
let matches = matchingTimeZones(abbreviation: "GMT+5:30")
If you print that result you will see one of them is "Asia/Calcutta"
(in an English locale).