Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return timezone name with Moment's guess()

I want to use Moment's guess() function to return the timezone continent (or country) and city as in their example:

moment.tz.guess(); // America/Chicago

But the above doesn't work. The returned value is CET, which is something else. It's an abbreviation of the Central European Time, i.e. no continent-country, no city.

How do I use the guess() function to return 'Europe/Stockholm', 'America/Chicago' etc?

like image 946
Fellow Stranger Avatar asked Dec 18 '22 03:12

Fellow Stranger


2 Answers

This happens when the host environment (browser, etc.) implements the API for ECMA-402 but returns the wrong type of time zone in the result. If you are seeing this with Moment, you can probably also get this result without Moment with the following:

Intl.DateTimeFormat().resolvedOptions().timeZone

Presently, Moment assumes that if this API exists, that it either provides a valid IANA time zone identifier or returns undefined. However, some environments return things like CET as you pointed out.

Ignoring bad results is already recorded as a feature request in moment/moment-timezone#423. In that particular case, the environment was an older Chrome browser on an Android device.

like image 136
Matt Johnson-Pint Avatar answered Dec 24 '22 00:12

Matt Johnson-Pint


I know I'm very late to this, but I was searching for an answer to the same problem. For anyone else looking for the same answer, using the following should work:

moment.tz.guess()

For reference, I'm using both moment-with-locales.js and moment-timezone-with-data.js, and just using the simple moment.tz.guess() will return the full timezone name for me, ie: America/Denver or America/New_York, etc.

like image 45
ryes31 Avatar answered Dec 24 '22 02:12

ryes31