Time (and more broadly speaking, localisation) is a commonly overlooked, and headache-inducing area of development. This is because time is defined by politics, rather than nature, and we haven’t got a consistent, global approach to time. There is no algorithm. It can be 3pm where you are, but 25 hours in the past 78 miles away (as is the case for Samoa and American Samoa). Most places offset their clocks by integer hours from GMT. Some don’t. Adelaide and Sydney are 30 minutes different. Some cities observe Daylight Saving Time, others don’t. Even if they are in the same country in the same longitude (e.g. Lindeman and Sydney in Australia).

So when I was developing my latest App, Clocks, I was at a loss as to how I was going to resolve this problem. For example:

  • If a user wants to display the time in Paris, how will I discover what time it is there?
  • If the timezone changes, how will I know to update the clock; should I perform a request on every launch?
  • There are databases of time zones, but they are somewhat overwhelming and it’s disheartening to have to include this in such a simple project, not to mention the extra development effort to parse it

So, for a while, I didn’t bother progressing the App. Then one day, I remembered about my newest friend, NSTimeZone.

I knew that NSTimeZone had the class method timeZoneWithName: but it didn’t occur to me that for this to work, it must know about a lot of time zones, and indeed you get the array of known time zones using knownTimeZoneNames; at the moment, this class will return you over 400 political time zones.

So what can you do once you have an NSTimeZone object for a particular time zone?

Well, firstly, you can find out what its offset from GMT is (secondsFromGMT), whether it’s Daylight Saving Time (isDaylightSavingTime), and if so what the offset it (daylightSavingTimeOffset).

You can even find out all this information for a given date, and find out when the next change to the time zone will occur (nextDaylightSavingTimeTransition).

Using this class, I was able to give the user a means to search for a time zone, and every time the App launches, the timezone offset would be correct – no network or external databases required!