2

Is it possible to get the user time zone in JavaSript in tz database format e.g. America/Los Angeles?

I noticed that when I create a Date object its toString method returns something like this:

Thu May 08 2014 08:40:48 GMT-0700 (Pacific Standard Time)

so maybe it's possible to change it to one of ids in tz database from this region (unfortunately chrome shows Pacific Daylight Time so it seems like there's no standard format to display). I need some library because I don't have time to right it myself with all possible combination and discrepancies in browsers like firefox vs chrome.

Alinoe
  • 73
  • 1
  • 10
  • You could try using `jstz`: http://pellepim.bitbucket.org/jstz/ – candu May 08 '14 at 15:59
  • possible duplicate of [JavaScript timezone information how to get America/Los\_Angeles (or equivalent)](http://stackoverflow.com/questions/22618056/javascript-timezone-information-how-to-get-america-los-angeles-or-equivalent) – Matt Johnson-Pint May 08 '14 at 16:26
  • jstz looks like what I was looking for. I'll give it a try. Thanks candu. – Alinoe May 08 '14 at 16:58

2 Answers2

0

Best answer I found so far

var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
console.log("The local time zone is: GMT " + gmtHours);
Md Sifatul Islam
  • 846
  • 10
  • 28
-2

From: http://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp

Return the timezone difference between UTC and Local Time:

var d = new Date()
var n = d.getTimezoneOffset();

The result n will be 420. Divide that by 60 to difference in hours.

You could then create an array populated text so that:

 timezoneArray[n] = "tz text description";
user3473534
  • 131
  • 1
  • 10
  • Does that get you `America/Los Angeles` ? – adeneo May 08 '14 at 16:08
  • It will if you populate the timezoneArray. This will have to be done manully: timezoneArray = ["tz 0", "tz 1", "tz 2", "tz 3", "tz 4", "tz 5", "tz 6", "America/Los Angeles" etc...]; – user3473534 May 08 '14 at 16:11
  • 1
    That's not how time zones work. You can't just map a single numeric offset back to a time zone identifier. See "Time Zone != Offset" in [the timezone tag wiki](http://stackoverflow.com/tags/timezone/info). – Matt Johnson-Pint May 08 '14 at 16:29
  • For clarity - recognize that `getTimeZoneOffset` works off a particular date. You may get a *different* offset depending on which date you call it on. The current offset is not necessarily the correct offset for the entire year or for all time. – Matt Johnson-Pint May 08 '14 at 17:51