How to set moment.js timezone when creating a date

The Problem

Since Moment.js is a library that runs client-side, when you create a new date using it; the constructor will take the current user’s timezone. This is not convenient when you want to display a list of dates that don’t depend on the user’s browser.

Let’s see an example of this, imagine you have an URL with an event that will start on Feb 15th, 2018 at 7 PM in the GTM-6 timezone, following table will be correct ONLY if you are in the GMT-6 timezone! because it represents hours in several timezones around the world taking that timezone as the relative time. This can be confusing for an user in Spain or for a visitor from New York.

Zone Time
America/Mexico_City 7pm CST
America/Bogota 8pm -05
America/Caracas 9pm -04
America/Lima 8pm -05
America/Guayaquil 8pm -05
America/Santiago 10pm -03
America/El_Salvador 7pm CST
America/Argentina/Buenos_Aires 10pm -03
Europe/Madrid 2am CET
America/Los_Angeles 5pm PST
America/Denver 6pm MST
America/New_York 8pm EST

Solution

Fortunately, Moment.js provides an out-of-the-box feature that allows to set the timezone we want to use when creating our original date, let’s see following code as an example:

var startDateAndTimeString = '2018-02-15 19:00:00';

// We set the timezone as a second parameter
var startDateAndTime = moment(startDateAndTimeString).tz('America/Mexico_City');

// Now, you could format your date to be displayed in different timezones
function formatDateToAnotherTimezone(anotherTimezone, startDateAndTime) {
 return moment(startDateAndTime).tz(anotherTimezone).format('ha z');
}

// This will get: 2am CET
var startDateAndTimeForMadridSpain =formatDateToAnotherTimezone('Europe/Madrid',startDateAndTime);

For this to work, please be sure you have loaded the Moment Timezone plugin.

That’s it! Awesome, isn’t it?

See you next time…

Leave a Reply

Your email address will not be published. Required fields are marked *