3

I am using jsTimezoneDetect script to detect user current timezone. Code below display result as America/Chicago. Is there a way to display CDT/CST (depending on today date)?

var timezone = jstz.determine();
timezone.name();

Or is there any other script I can use?

αƞjiβ
  • 3,056
  • 14
  • 58
  • 95

2 Answers2

8

First understand:

  • A time zone abbreviation is potentially ambiguous (5 different CST's).
  • Not all time zones have meaningful abbreviations. Some are just made up to complete the API, but not actually used by people in the region (MSK in Belarus).
  • There are often disagreements about the correct abbreviation to use (HST vs HAST).
  • They are usually in English, though other languages may have different abbreviations for the same time zone. (PST vs HNP (French))
  • The abbreviation depends highly on the specific date chosen - as it could change for daylight saving time (EST vs EDT).

In many browsers, you can get the abbreviation directly (via ECMA-402) by:

const d = new Date(); // now, or the specific date in question
const tz = d.toLocaleString('en', {timeZoneName: 'short'}).split(' ').pop();
console.log(tz);

This doesn't necessarily work everywhere though.

Since you're working with jsTimeZoneDetect, you already have an IANA time zone identifier ("America/Chicago"). So, you could get it from moment-timezone, like this:

var m = moment(); // now, or the moment in question
var s = m.tz('America/Chicago').format('z');

That will work everywhere, but you have the overhead of moment and moment-timezone, and jstz, which is probably overkill unless you are using these libraries for other purposes anyway.

You might also consider a server-side solution. For example, if you're using PHP, you can use this code. Or, if you're using .NET, you can use my TimeZoneNames library.

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • Under the hood it uses `zoneAbbr()` so, you could do something like `const abbrTz = moment.tz('America/Chicago').zoneAbbr();` to get the abbreviated Time Zone. Additionally, if you want `moment` to guess the user's/browser's local Time Zone then you could do something like this: `const abbrLocalTz = moment.tz(moment.tz.guess()).zoneAbbr();` note that `guess()` is a method off the `tz` property object not the `tz()` method. – Al Dass Sep 18 '18 at 16:41
-2

In native JS you could:

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

and then go over it with a switch.

Inuyaki
  • 1,009
  • 7
  • 9
  • Many time zones use the same offset. One cannot determine a time zone or abbreviation by offset alone. See [this list on wikipedia](https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations) for examples. – Matt Johnson-Pint May 23 '15 at 02:27
  • perhaps, but i doubt that it will affect someone regionally. In my case, we only deal with four time zones so a case statement is conceivably a solution. – John Lord Dec 17 '19 at 20:39