Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect timezone abbreviation using JavaScript

I need a way to detect the timezone of a given date object. I do NOT want the offset, nor do I want the full timezone name. I need to get the timezone abbreviation.

For example, GMT, UTC, PST, MST, CST, EST, etc...

Is this possible? The closest I've gotten is parsing the result of date.toString(), but even that won't give me an abbreviation. It gives me the timezone's long name.

like image 394
Stephen Sorensen Avatar asked Dec 23 '09 18:12

Stephen Sorensen


People also ask

How does JavaScript detect timezone?

The getTimezoneOffset method returns the difference, in minutes, between a date (evaluated in UTC) and the same date evaluated in the visitor's local time zone. If you get a value like -120 , then the time zone offset is UTC+02. Similarly, for a value of -60 , the time zone offset is UTC+01.

How can I get the timezone name in JavaScript?

In javascript , the Date. getTimezoneOffset() method returns the time-zone offset from UTC, in minutes, for the current locale.

How do you get time zone abbreviation in moment?

As of version 0.5. 0, you can now guess the user's local time zone, which when combined with the above technique, allows you to do the following: moment(). tz(moment.

What is getTimezoneOffset in JavaScript?

The getTimezoneOffset() method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone.


2 Answers

A native solution:

var zone = new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2] console.log(zone)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

You can pass undefined instead of en-us to default to the browser's current locale.

like image 161
Stephen DuMont Avatar answered Nov 01 '22 08:11

Stephen DuMont


moment-timezone includes an undocumented method .zoneAbbr() which returns the time zone abbreviation. This also requires a set of rules which are available to select and download as needed.

Doing this:

<script src="moment.js"></script> <script src="moment-timezone.js"></script> <script src="moment-timezone-data.js"></script> <script>     moment().tz("America/Los_Angeles").zoneAbbr(); </script> 

Returns:

'PDT' // As of this posting. 

Edit (Feb 2018)

Evan Czaplicki has worked on a draft proposal to add a time zone API to browsers.

like image 26
absynce Avatar answered Nov 01 '22 07:11

absynce