Get timezone from users browser using moment(timezone).js

nemo_87 picture nemo_87 · Nov 3, 2016 · Viewed 108.4k times · Source

What is the best way to get client's timezone and convert it to some other timezone when using moment.js and moment-timezone.js

I want to find out what is clients timezone and later convert his date and time into some other timezone.

Does anybody has experience with this?

Answer

Matt Johnson-Pint picture Matt Johnson-Pint · Nov 3, 2016

When using moment.js, use:

var tz = moment.tz.guess();

It will return an IANA time zone identifier, such as America/Los_Angeles for the US Pacific time zone.

It is documented here.

Internally, it first tries to get the time zone from the browser using the following call:

Intl.DateTimeFormat().resolvedOptions().timeZone

If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.

If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.