Skip to main content

Use Moment Timezone javascript library to work with timezones

Dec 11 '15
moment timezone javascript

Anyone who's worked with date and time in a Web application knows that when it comes to time zones, things get a little bonkers. Add in Daylight Savings Time (DST), recent controversy around leap seconds, and Arizona, and you've got a daunting problem.

PHP has a pretty solid library for time zones. It uses time zones defined in the tz database maintained by IANA, such as America/Los_Angeles for PST and America/New_York for EST. The database takes into account historical data, variations within certain countries or regions, DST, and leap seconds. This library is compiled by default in the server's PHP library and is ready to use.

But javascript, alas, does not have such a robust library. Browsers make local time available, javascript knows about UNIX timestamps, and has low-level parsing and conversion functions, but how can we work with with human-readable, localized time objects in a way that won't make us question our sanity?

We encountered this problem on a recent project. The client asked us to remove phone support hours after their office closes in San Francisco, at 5 pm Pacific Standard Time. If we calculated this using GMT offsets, PST is GMT -8 hours. But during DST, it's GMT -7. So we can't simply subtract by 8...

Enter Moment. This library is a fantastic API for generating mutable date objects that fills in a lot of gaps in Javascript's basic date functions. Moment Timezone is an extension to the API which includes an export of the same tz database that PHP has. This allows us to use all our favorite named time zones to generate a moment() object, and we can add and subtract days and hours using Moment's API.

So, for this problem, we used the following code:

// Hide phone support wait times outside of business hours.
var pacificMoment ="America/Los_Angeles");
var pacificTimeWeekday = pacificMoment.format('e');
var pacificTimeHour = pacificMoment.format('H');
if (pacificTimeWeekday < 1 || pacificTimeWeekday > 5 || pacificTimeHour < 5 || pacificTimeHour > 16) {

pacificMoment is the current time in PST. From then on we just check that the hour is 17 or above (17 = 5 pm). Easy.

Leveraging well-supported third-party Javascript APIs like Moment and Moment Timezone makes dealing with complex problems like time zone offsets a delight. Consider contributing to the project to help keep these invaluable open source libraries going strong!