Handling timezones with daylight savings in moment.js

Moment.js is a fantastic library for managing dates in Node.js or other javascript applications.  If you’re reading this article it probably means you’ve used moment.js before in your application, but if not, definitely give it a try.  This article will focus mainly on how to use timezones in your moment.js javascript application.

Moment.js handles basic timezone capabilities with their default library, however it doesn’t have the ability to convert times between different timezones based on geographic locations and take daylight savings time into consideration.

For example, let’s say the server running your node.js application was in Los Angeles and therefore had a local time of 3pm but you wanted to display the current time in New York?

The answer is moment-timezone.

This is a library from the same smart people that made the moment library but it also includes information about timezones around the world which allows you to easily convert between the different times.  It’s important to note that the extra timezone info does take up space, so the moment-timezone library is bigger than the standard moment library.  The moment team provides good documentation on the website, but there is also a quick example below (for node.js).

To install the module, it’s the usual:

npm install moment-timezone

And then in your code you can do something like this:

// First we include our moment-timezone
var moment = require('moment-timezone');

// Now create a moment object, just like any other
var my_moment = moment();

// my_moment now has the current local time (from your server)
console.log("Server Time: " + my_moment.format());

// To convert it to New York time, you use the tz function
my_moment.tz('America/New_York');

console.log("New York: " + my_moment.format());

The code above will output the date/time from your server and then the current date/time in New York.

It’s important to note that you can’t just use *any* city name.  The tz function takes the name of a standard linux TZ timezone name.  You can see a list of these in this wikipedia article.  Typically you would use a nearby city that is on the same daylight savings schedule (if any) as the date/time you want to display.  You can also use some of the short-hands provided like “US/Mountain” which displays time in MST/MDT (using daylight savings when appropriate).

Working with times and timezones can get confusing at times, but the moment-timezone library for javascript and node.js takes a lot of the complexity out of it.

Leave a Comment