-1

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?

IKKA
  • 6,297
  • 7
  • 50
  • 88

1 Answers1

3

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).

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • @rmaddy , How can I convert timezone identifier to abbreviation? (For example how can I convert 'Asia/Kolkata' to '+05.30') – IKKA Aug 16 '19 at 09:25
  • @IKKA Create a `TimeZone` using the `"Asia/Kolkata"` identifier. Then get that time zone's `abbreviation`. That's been covered in other question. Please do some searching if you need further assistance with your new question. – rmaddy Aug 16 '19 at 15:21