Get client timezone (not GMT offset amount) in JS

后端 未结 5 2111
时光说笑
时光说笑 2020-12-14 18:04

I need to determine the client timezone (e.g. CET, GMT, EST) in JS. Getting the offset is straightforward, but doesn\'t have all the info necessary to determine the TZ, at l

5条回答
  •  时光取名叫无心
    2020-12-14 18:28

    You could scrape it from a date object's toString() method. new Date.toString() results in something like Wed Sep 19 2012 10:04:32 GMT-0400 (Eastern Daylight Time) in Firefox, Safari and Chrome. The data you want is there -- the capital letters within the parentheses. All that's needed is to scrape them.

    In the case of Internet Explorer, the result of toString() already includes the EDT.

    In the case of Opera, your only option is to settle for GMT-0400 or similar. There's nothing scrape-able in the toString() method.

    var now = new Date().toString();
    var TZ = now.indexOf('(') > -1 ?
    now.match(/\([^\)]+\)/)[0].match(/[A-Z]/g).join('') :
    now.match(/[A-Z]{3,4}/)[0];
    if (TZ == "GMT" && /(GMT\W*\d{4})/.test(now)) TZ = RegExp.$1;
    

    Example results:

    • Firefox: TZ = "EDT"

    • Safari: TZ = "EDT"

    • Chrome: TZ = "EDT"

    • IE: TZ = "EDT"

    • Opera: TZ = "GMT-0400"

    Seems to work just as well with all the random Asian and European time zones I tried as well, returning WPST for Guam (West Pacific Standard Time), MPST for Kuala Lumpur (Malay Peninsula Standard Time), etc; and degrades peacefully to GMT+0X00 notation where the browser doesn't supply the name (Perth, for example).

提交回复
热议问题