Timezones and date manipulation in JavaScript

February 03, 2012

One issue with web development is that your applications are immediately available to the world. As such, you want your application to work well for whoever is using it, and a big part of who someone is, is where they live.

Where you live determines what language you speak, what units you measure with, etc. Another important aspect of location is time, and the fact that each location has its intricacies about how it deals with time, whether it be timezones, daylight savings, or what day the week starts.

Fortunately, JavaScript has native support for time, and for the timezone the user is currently located in. Unfortunately, your user might travel, or your app might require collaboration across continents. How do you deal?

As far as I know, there isn’t a single JavaScript library that supports both full timezone support and easy date manipulation. But there are two that are highly helpful for each of these tasks.

TimezoneJS creates a new TimezoneJS.Date object which has native timezone support using Olson TZ data files. Although it requires you to use a new Date object, its quite helpful in enabling the use of any timezone you want, as long as you keep those timezone files up to date.

Datejs is a great, albeit, old library that extends the prototype of the native JavaScript Date object to add incredibly useful helper methods and pretty date printing (another core feature missing from the native object). Another overlooked feature of Datejs is that its maturation means globalization support in the form of Culture files, which define how different parts of the world think of time.

Obviously, using both of these standalone is possibly, but switching between objects can be cumbersome, so I began the process of making Datejs work for the TimezoneJS.Date object.

For this to work, simply use TimezoneJS, add a culture file from Datejs’s repo, and add timezone-js-sugar. The timezone-js-sugar package is simply a port of Datejs’s core, but gives you a bunch of helpful helpers and pretty date printing.

Side notes:

  • timezone-js require Fleegix out of the box, however, you can also use it with jquery just by adding the timezone-js-jquery add on

  • I’ll be making some bug fixes to timezone-js at here


© 2023 Viraj Sanghvi