Search code examples
javascriptjquerydatetimetimezonejstimezonedetect

Display three letters time zone code using jsTimezoneDetect script


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?


Solution

  • 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.