Calculate the UTC offset given a TimeZone string in JavaScript

前端 未结 5 2066
感情败类
感情败类 2020-12-06 11:00

Using the standard JS library (ECMA5), without using momentjs or external libs, how do you calculate the UTC offset given a TimeZone string such as \"Europe/Rome\"

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 11:25

    The chosen answer doesn't really answer the question. What the author want is a function that can input a timezone name and then return an offset.

    After some investigations and digging the source code of icu4c, turns out the follow snippet can do what you need:

    const getUtcOffset = (timeZone) => {
      const timeZoneName = Intl.DateTimeFormat("ia", {
        timeZoneName: "short",
        timeZone,
      })
        .formatToParts()
        .find((i) => i.type === "timeZoneName").value;
      const offset = timeZoneName.slice(3);
      if (!offset) return 0;
    
      const matchData = offset.match(/([+-])(\d+)(?::(\d+))?/);
      if (!matchData) throw `cannot parse timezone name: ${timeZoneName}`;
    
      const [, sign, hour, minute] = matchData;
      let result = parseInt(hour) * 60;
      if (sign === "-") result *= -1;
      if (minute) result + parseInt(minute);
    
      return result;
    };
    
    console.log(getUtcOffset("US/Eastern"));
    console.log(getUtcOffset("Atlantic/Reykjavik"));
    console.log(getUtcOffset("Asia/Tokyo"));

    Note that the locale ia used here is Interlingua. The reason is that according to the source code of icu4c, the timezone name differs per locale. Even you use the same locale, the format of the timezone name can still vary based on different timezone.

    With Interlingua (ia), the format is always the same pattern like GMT+NN:NN which can be easily parsed.

    It's a little tircy but it works well in my own products.

    Hope it helps you as well :)

提交回复
热议问题