swiftnstimezone

Getting timezone abbreviations in Swift


I am trying to retrieve the timezone abbreviations of the local time zone by using the following code.

private func getLocalTimezone() -> String {
   guard let localTimezone =  TimeZone.current.abbreviation() else {
     return ""
   }
   return localTimezone
 } 

But when I am in Indian time zone I am always getting GMT+5:30 where I need it as IST. Its coming correctly when I am in CST or PST. Can anyone please suggest a way to reach to the solution for this issue. Thanks a lot in advance


Solution

  • This is because time zone abbreviations are locale sensitive. IST only means India Standard Time (Asia/Kolkata) in India. In other parts of the world, it could mean Israel Standard Time, or Irish Standard/Summer Time. Here's a site that shows you the list of abbreviations. You can see for yourself how ambiguous they can be.

    This is why abbreviation() takes into account the region of your phone, i.e. this setting:

    enter image description here

    abbreviation() will give you "IST" if your device's region is India. If your phone is somewhere else, it shows "GMT+5:30" because that is the safest, most unambiguous option.

    If you want it to output IST no matter where your device is, you need to hard code this by creating a dictionary of time zone identifiers to abbreviations that you want. There is a built in abbreviationDictionary that goes the other way - abbreviations to identifiers. You can search it, and it will work for IST (Asia/Kolkata), but might not work for whatever other time zone that you are interested in.

    let abbreviation = TimeZone.abbreviationDictionary
        .first(where: { $1 == TimeZone.current.identifier })?.key
    

    and I'm not sure whether the contents of this dictionary will stay the same in future versions of iOS. Use it at your own risk.