Search code examples
iosswiftnstimezone

What is the proper format for setting TimeZones in iOS ?


I've tried using this Wiki to get the appropriate abbreviation for time zones to use in:

let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = formatString
        dateFormatter.timeZone = NSTimeZone(abbreviation: setZone)

and "GMT" works as does "GST", but for some reason a good portion of the abbreviations do not work (for example GYT). Is there some other format that I should be using ? I have also tried passing in UTC-X also but that didn't work either


Solution

  • Here is function I call from a NSTimer...

    self.clock = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.updateClock), userInfo: nil, repeats: true)
    
    func updateClock() {
          dispatch_async(dispatch_get_main_queue()) {
            let date = NSDate();
            // "Apr 1, 2015, 8:53 AM" <-- local without seconds
    
            var formatter = NSDateFormatter();
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    
            _ = formatter.stringFromDate(date);
                        // "2015-04-01 08:52:00 -0400" <-- same date, local, but with seconds
            formatter.timeZone = NSTimeZone(abbreviation: "CET");
            let cetTimeZoneStr = formatter.stringFromDate(date);
            // "2015-04-01 12:52:00 +0000" <-- same date, now in UTC
    
            self.timer.text = cetTimeZoneStr
    
    
        }
    }
    

    And here some code to get the timezones known to the system!

    let blah = NSTimeZone.knownTimeZoneNames()
    let blah2 = NSTimeZone.abbreviationDictionary()
    print("\(blah) \(blah2)")