Calculate the UTC offset given a TimeZone string i

2019-01-28 04:34发布

问题:

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" or "America/Los_Angeles"?

UTC Offsets may depend on whether it is DST or not, so it would make sense if the solution required converting the local client date to the specified Timezone String. The goal is just to know the offset from UTC.

function getUtcOffset(timezone) {
  // return int value. 
  // > 0 if +GMT 
  // < 0 if -GMT.
}

回答1:

There is no function in ECMAScript (ECMA-262) that can perform the operation you requested. This is simply because standard ECMAScript does not know anything about time zones other than that of the local computer, and UTC.

However, in browsers that support the ECMAScript Internationalization API (ECMA-402), and fully support the IANA time zone database identifiers, you can hack together a function like this:

function getTimezoneOffset(d, tz) {
  var a = d.toLocaleString("ja", {timeZone: tz}).split(/[\/\s:]/);
  a[1]--;
  var t1 = Date.UTC.apply(null, a);
  var t2 = new Date(d).setMilliseconds(0);
  return (t2 - t1) / 60 / 1000;
}

This will work in current versions of Chrome, and perhaps in a few other places. but it is certainly not guaranteed to work everywhere. In particular, it won't work in Internet Explorer browsers of any version.

Example usage (in Chrome):

getTimezoneOffset(new Date(2016, 0, 1), "America/New_York") // 300
getTimezoneOffset(new Date(2016, 6, 1), "America/New_York") // 240
getTimezoneOffset(new Date(2016, 0, 1), "Europe/Paris") // -60
getTimezoneOffset(new Date(2016, 6, 1), "Europe/Paris") // -120

A few things to note about this particular function:

  • Like I mentioned, It's not going to work everywhere. Eventually, as all browsers catch up to modern standards it will, but it won't currently.

  • The date you pass in will indeed affect the result. This is due daylight saving time and other time zone anomalies. You can pass the current date just with new Date(), but the result will change based on when you call the function. See "time zone != offset" in the timezone tag wiki.

  • The results of this function are the same as Date.getTimezoneOffset - in terms of minutes, with positive values being West of UTC. If you are working with ISO8601 offsets, you'll need to convert to hours and invert the sign.

  • The function relies on the time zone formatting functionality of the toLocaleString function. I picked the 'ja' culture, because the date parts were already in the correct order for the array. This is a hack indeed. Ideally there would be an API that would let you access time zone information without binding it to a locale when formatting. Unfortunately, the designers of this particular API have made the mistake of associating time zone with locale. This is a mistake that's been made in a few other APIs from various languages, and unfortunately was carried into JavaScript here.

    Restated plainly: The only time zone functionality in ECMA-402 is to apply a time zone when formatting a string, which is a design flaw, IMHO.

  • There's a bug in my example usage section above, that exemplifies part of why this API is a mistake. Specifically, there's no way to specify a time zone when you create a Date object. The Jan 1st and July 1st dates I pass in are created in the local time zone, not in the time zone specified. Therefore, the output may not be exactly what you expect near a transition. This could be hacked even more to work around this problem, but I will leave that as an exercise to you.

Again - Though this answer satisfies the criteria asked for, as there are no external libraries involved, I strongly recommend against using this in any production code. If you're planning on doing anything important with this, I'd use one of the libraries I listed here. My personal preference is for moment.js with the moment-timezone addon, because I help maintain that library. YMMV



回答2:

Did you check moment-timezone?

moment.tz("America/Los_Angeles").utcOffset();


回答3:

For others who may land on this question, there is a method available on the standard Date function in JavaScript to get the offset from UTC called getTimezoneOffset.

Usage is simply (for example): new Date().getTimezoneOffset(). This returns the number of minutes the current timezone is from UTC. NOTE: It returns a negative number if the current timezone is ahead of UTC. For example, if the user's timezone is UTC+1, -60 is returned.