0

I want to show timezone as "IST", "EST", etc. That seems to be simple but there is an issue.When I use following code:

let timeZone = TimeZone.current.abbreviation()

For India I get "GMT+5:30" but for Toronto, I get "EDT". Please help, or let me know some other way to show such abbreviations.

EDIT 1

I came up with a workaround but still, sometimes I get some weird timezones:

func getTimeZoneAbbrevation() -> String {
    var returnTimeZone = ""
    let timezone = TimeZone.current.identifier
    let dict = TimeZone.abbreviationDictionary
    for (key,value) in dict {
        if value == timezone {
            returnTimeZone = key
            break
        }
    }
    if returnTimeZone == "" {
            if let timezone = NSTimeZone.default.abbreviation() {
                returnTimeZone = timezone
        }
    }
    return returnTimeZone
}

EDIT 2: Playground code using kamaldeep's solution

user832
  • 796
  • 5
  • 18
  • Have you checked this? https://stackoverflow.com/questions/27053135/how-to-get-a-users-time-zone – Kamaldeep singh Bhatia Apr 20 '18 at 10:20
  • @kamaldeepsinghbhatia yes, I have already checked it, check my edit 1, I have implemented that code in my function, but the issue with that is, for Toronto it returns me "America/Toronto", which is not present in the abbreviationDictionary. – user832 Apr 20 '18 at 10:24
  • 1
    Note that you *should* be getting `"EDT"` for Toronto right now, because that is the *current* time zone abbreviation. They are currently in Eastern Daylight Time. – Matt Johnson-Pint Apr 20 '18 at 17:50

2 Answers2

0

This should work.

let someTime = TimeZone(identifier: "America/Toronto")
let timezone = someTime?.abbreviation()

Now timezone contains value "EDT" so you can directly use this.

Just FYI if you want to check for these identifier so you can get it from

var timeZoneIdentifiers: [String] { return TimeZone.knownTimeZoneIdentifiers }

I hope this will help now.

0

Try this

let timeZoneDict = TimeZone.abbreviationDictionary.filter {
$0.value == TimeZone.current.identifier
}
if !timeZoneDict.isEmpty {
let timeZone = timeZoneDict.first?.key
print(timeZone)
}

Prateek kumar
  • 244
  • 3
  • 9