Detect timezone abbreviation using JavaScript

后端 未结 16 2132
清酒与你
清酒与你 2020-11-30 02:17

I need a way to detect the timezone of a given date object. I do NOT want the offset, nor do I want the full timezone name. I need to get the timezone abbreviation.

16条回答
  •  春和景丽
    2020-11-30 02:54

    This works perfectly in Chrome, Firefox but only mostly in IE11. In IE11, timezones without straight forward abbreviations like "Indian Chagos Time" will return "ICT" instead of the proper "IOT"

    var result = "unknown";
    try{
        // Chrome, Firefox
        result = /.*\s(.+)/.exec((new Date()).toLocaleDateString(navigator.language, { timeZoneName:'short' }))[1];
    }catch(e){
        // IE, some loss in accuracy due to guessing at the abbreviation
        // Note: This regex adds a grouping around the open paren as a
        //       workaround for an IE regex parser bug
        result = (new Date()).toTimeString().match(new RegExp("[A-Z](?!.*[\(])","g")).join('');
    }
    console.log(result);
    

    Result:

    "CDT"
    

提交回复
热议问题