core
core

Reputation: 33079

Getting timezone label in JavaScript

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?

Upvotes: 0

Views: 376

Answers (4)

jossiwolf
jossiwolf

Reputation: 2175

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.

Upvotes: 0

1000111
1000111

Reputation: 13519

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(")"));
}

Upvotes: 1

Bosworth99
Bosworth99

Reputation: 4234

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"

Upvotes: 1

nils
nils

Reputation: 27184

You could use a regular expression to get it:

var d = new Date().toString();
var timezone = d.match(/\(([^)]+)\)/)[1];

Upvotes: 0

Related Questions