TimeZones with Javascript

posted by sacah on javascript, programming,

So I originally wanted to make a TimeZone selector similar to most OSes, you know, the world map with cities visible and you can select the one in your time zone. The thing I didn't want to do with this was all the work of building and maintaining a DB of cities and their GMT offset along with daylight saving rules.

So I looked around and found a time zone database, now hosted at http://www.iana.org/time-zones. I downloaded these and started writing my JS library to parse the list and generate the rules for all the time zone info. And thus jsTimeZone was born.

With this library it allows you to find the date/time in a time zone similar to most BE languages, so using 'Australia/Sydney', or 'Europe/London'. Being FE based, it will calculate based on the machines local date/time, so as long as it's accurate, this library should get the right result.

The added benefit to using this is when I go to make the map, I can just scan through the time zone info and I'll have city name and country all ready to look up GPS coordinates for and plot on my map. Though this one I'll generate once and include a static file in the repo to be used, along with a generation script in case new time zones popup down the track.

I have only tested a few of the more common time zones I use, let me know if any places don't return the right result.

You can also export the tz database from the module and use the returned JSON string when calling the module again.

Quick example of using this module
function queryTime() {
var ausSyd=jsTZAll.offsetIn('Australia/Sydney');
console.log('Aus - Syd: %o', ausSyd.getOffset());
console.log('Aus - Syd: %o', ausSyd.date());
}

var jsTZAll=jsTimeZones('australasia', 'europe');
jsTZAll.init(queryTime);
Which will return

Aus - Syd: { hr: 11, min: 0}
Aus - Syd: Date {Fri Feb 22 2013 15:06:59 GMT+1100 (AUS Eastern Daylight Time)}

To see more, head over to the Bitbucket repo at jsTimeZone.