Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

datetime - Calculate the UTC offset given a TimeZone string in JavaScript

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.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) {
  const a = d.toLocaleString("ja", {timeZone: tz}).split(/[/s:]/);
  a[1]--;
  const t1 = Date.UTC.apply(null, a);
  const 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...