Topics

#66: NSTimeZone ⏰

Topics

Ask any engineer, time zones are the worst.

Don't worry, NSTimeZone has our backs. It can help us easily translate NSDate objects from one time zone to another. Let's dive deeper with a concrete example.

Here's a common scenario:

We're working on an app that downloads some data from an API, then displays it to the user. In our case, we know the API is returning timestamp information in the GMT time zone.

Translating the API's values to the user's local time zone would go something like this:

let input = "2015-08-24T09:42:00" // came from HTTP API

let GMTTZ = NSTimeZone(forSecondsFromGMT: 0)
let localTZ = NSTimeZone.localTimeZone()

let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
formatter.timeZone = GMTTZ

if let date = formatter.dateFromString(input) {
    formatter.timeZone = localTZ
    formatter.dateFormat = "MMMM d, H:mm a"

    timestampLabel.text = formatter.stringFromDate(date)
  // "August 24, 2:42 AM"
}

After we parse the date, we change our formatter's time zone to the local one, then render our date back to a string to show the user.

The NSTimeZone.localTimeZone() function (as well as any NSTimeZone object) is our gateway to a few more useful values:

localTZ.secondsFromGMT // -25200
localTZ.abbreviation // "PDT"
localTZ.name // "America/Los_Angeles"

There's also a way to get a more human-friendly name, with a few built-in styles. We're using .Generic here:

localTZ.localizedName(
  .Generic,
  locale: NSLocale.currentLocale()
) // "Pacific Time"

Don't let the insanity of time zones scare you away from making your app work well in any location. Remember, Foundation has your back.