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

81

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?

This question is tagged with javascript momentjs angular-moment

~ Asked on 2016-11-03 12:29:49

The Best Answer is


17

var timedifference = new Date().getTimezoneOffset();

This returns the difference from the clients timezone from UTC time. You can then play around with it as you like.

~ Answered on 2016-11-03 12:47:38


229

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.

~ Answered on 2016-11-03 16:54:57


Most Viewed Questions: