Detect timezone abbreviation using JavaScript

后端 未结 16 2159
清酒与你
清酒与你 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:59

    Using contents from new Date().toString()

    const timeZoneAbbreviated = () => {
      const { 1: tz } = new Date().toString().match(/\((.+)\)/);
    
      // In Chrome browser, new Date().toString() is
      // "Thu Aug 06 2020 16:21:38 GMT+0530 (India Standard Time)"
    
      // In Safari browser, new Date().toString() is
      // "Thu Aug 06 2020 16:24:03 GMT+0530 (IST)"
    
      if (tz.includes(" ")) {
        return tz
          .split(" ")
          .map(([first]) => first)
          .join("");
      } else {
        return tz;
      }
    };
    
    console.log("Time Zone:", timeZoneAbbreviated());
    // IST
    // PDT
    // CEST

提交回复
热议问题