Dealing with timezones using moment.js

Dealing with timezones using moment.js

This document covers common use cases one may have to deal with while handling timezones in applications.

The local time within a time zone is defined by its offset (difference) from Coordinated Universal Time (UTC), the world’s time standard.

To work with timezones in moment we need moment.js core, moment-timezone.js and timezone data.

An npm package, moment-timezone (https://www.npmjs.com/package/moment-timezone) provides a wrapper in react for moment.js with timezone data, so no additional code is needed for loading data.

Get a list of all timezones:

 

This method returns an array of close to 600 timezone identifiers. These timezones are obtained from IANA timezone database and new versions are released as timezone laws change in various countries.

 

Get a list of all countries

 

This method returns a list of all country codes. A country may have more than one time zone.

Get list of timezones for a particular country:

 

 

Creating a moment in the local timezone: The zonesForCountry() method takes in country code and returns an array of all the timezones in the country, sorted alphabetically.

The moment constructor returns an object in the context of the user’s local time.

 

Using timezones

Getting time in a particular timezone:

 

It takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier. You can initialize a moment object

 

Getting utc offset in a specific timezone

A UTC offset is a value that represents how far a particular date and time is from UTC. It is expressed in the format ±HH:mm most of the time.

 

This method returns an offset from UTC time in minutes.

Converting between timezones:

 

Note that moment objects are mutable, so you may want to clone the object you’re working on by calling moment() or clone() on a moment.

 

Guessing user’s timezone:

 

Moment Timezone uses the Internationalization API Intl.DateTimeFormat().resolvedOptions().timeZone in supported browsers to determine the user’s timezone.

 

Note: After September 2020, moment.js is no longer a project in active development, and thus no new versions would be released, but timezone data would be kept updated. Some alternate libraries they recommend: Luxon, Intl API, day.js, day-fns.

 

References: https://momentjs.com/timezone/docs/

Comments