Jason M
Jason M

Reputation: 1053

what method can I use to get the timezone abbreviation in all browsers?

In Chrome, Safari, and Firefox I'm using a call like this:

var date = new Date();
date.toTimeString().match(/\((.*)\)/)

But this doesn't work in IE 9 because IE 9 returns it's data without the parenthesis. And this doesn't work in IE 11 because IE 11 doesn't return the abbreviation but instead returns something like (Pacific Standard Time).

Example IE9-IE10 output:

"15:38:43 PST"

Example IE11 and Edge output:

"15:36:07 GMT-0800 (Pacific Standard Time)"

Upvotes: 4

Views: 1963

Answers (3)

Dipu R
Dipu R

Reputation: 575

Try

Intl.DateTimeFormat().resolvedOptions().timeZone

Waring: It is not compatible with all browser version

Upvotes: 0

RobG
RobG

Reputation: 147513

Some background:

  • Time zone names and their abbreviations aren't officially standardised, though there are a number of schemes that have been widely adopted and might be considered de facto standards (e.g. IANA time zone database)
  • Browsers are notoriously bad at internationalisation, e.g. IE and Chrome report times for eastern Australia as "E. Australia Standard Time" when it is known much more widely as "Australian Eastern Standard Time"
  • Some time zone schemes do not have unique identifiers for every time zone, e.g. EST might apply to 3 different zones.
  • The value returned by toTimeString is entirely implementation dependent, so it may not contain any time zone information at all and even if it does, it may not be what the user expects (see above)

There are various libraries that determine likely time zones based on the time zone offset returned by Date.prototype.getTimezoneOffset and testing for 2 dates to see if daylight saving is used (e.g. jsTimezoneDetect), however most are based on the IANA time zone database.

So to rephrase your question:

Is there a reliable method to get the host time zone abbreviation

The answer is no.

However, if you're prepared to accept derived IANA time zone designations and map them to whatever other scheme you wish to employ, then using a library will get fairly close.

Upvotes: 3

Jared Dykstra
Jared Dykstra

Reputation: 3626

MomentJS Timezone:

moment.tz([2012, 0], 'America/New_York').format('z');    // EST
moment.tz([2012, 5], 'America/New_York').format('z');    // EDT
moment.tz([2012, 0], 'America/Los_Angeles').format('z'); // PST
moment.tz([2012, 5], 'America/Los_Angeles').format('z'); // PDT

Upvotes: 2

Related Questions