0

I know JavaScript Date objects contain getTimezoneOffset() for getting the offset, but is there any method that returns the label or name for that timezone?

For example, on my computer, in Chrome's console, if I do:

> new Date().toString();

Then I get:

< "Thu Feb 25 2016 08:49:56 GMT-0800 (Pacific Standard Time)"

What I'd like to do is take a Date and get back "Pacific Standard Time" portion for it.

Is this possible, and if so, how?

core
  • 32,451
  • 45
  • 138
  • 193

4 Answers4

1

I dont think there is a reliable way without regex matching (see @nils answer). Not sure what caveats that date string comes with, so might be fragile? It looks like there are some libraries available that can simplify this

https://bitbucket.org/pellepim/jstimezonedetect/wiki/Home

var timezone = jstz.determine();
timezone.name(); 
"Europe/Berlin"
Bosworth99
  • 4,206
  • 5
  • 37
  • 52
  • 1
    That is about the only reasonably reliable way. Such libraries test for the current timezone offset and at times either side of common daylight saving boundaries. The two allow reasonably accurate detection of [*IANA timezone*](https://www.iana.org/time-zones). However, accuracy for historical dates is suspect as javascript only considers current settings as if they had existed always. – RobG Feb 25 '16 at 21:14
1

There's no straight forward way. You can get it through the following method.

Alternatively you can choose REGEX.

function getTimeZoneLabel(){
   var str = new Date().toString();
   return str.substring(str.indexOf("(")+1,str.indexOf(")"));
}
1000111
  • 13,169
  • 2
  • 28
  • 37
0

You could use a regular expression to get it:

var d = new Date().toString();
var timezone = d.match(/\(([^)]+)\)/)[1];
nils
  • 25,734
  • 5
  • 70
  • 79
  • That assumes that *Date.prototype.toString* returns values in a particular format. However, it's entirely implementation dependent, the string may not contain any timezone at all and if it does, not in a format that matches the regular expression. So there is no certainty that it will work. – RobG Feb 25 '16 at 21:08
  • Thank you for pointing this out, I figured that the output was standardized. In all modern browsers (Chrome, FF, Safari, Opera and IE 11) and node.js, the output seems to be consistent though. – nils Feb 26 '16 at 08:08
0

An approach would be to just get what's inside the paranteses. Juan Mendes posted a solution:

function getTimeZone() {
    return /\((.*)\)/.exec(new Date().toString())[1];
}

getTimeZone();

Note that this is language, OS and browser specific (and therefor of course not the ideal solution). If it is however okay for you to use a library, you could use jsTimezoneDetect.

Community
  • 1
  • 1
jossiwolf
  • 1,865
  • 14
  • 22