Get current GMT offset from a timezone identifier

本秂侑毒 提交于 2021-02-11 15:36:13

问题


How do I get the current GMT offset from a timezone identifier? Ideally, it would include the long form name too.

For example:

"America/Los_Angeles"  //output: GMT-0700 (Pacific Daylight Time)

It would be nice if it worked with ISO strings too, for example:

2020-12-21T03:57:00Z   //output: GMT-0800 (Pacific Standard Time)

回答1:


You can use the timeZone and timeZoneName options of the Intl.DateTimeFormat object as below to get the name of more common timezones, but lesser known ones will probably be missing. Also:

  1. You can't get them both in the same call, so you need to call it twice
  2. In some cases, you'll just get short and long names without the actual offset
  3. Timezone names aren't standardised, so different implementations may return different names, or just the actual offset without a name.
  4. You'll get the offset for the date and time that you create, not the date and time for the location, so it may be wrong if that difference crosses a daylight saving boundary

e.g.

// Get short offset, might show the actual offset but might be a short name
let formatterA = new Intl.DateTimeFormat('en',{timeZone:'America/New_York', timeZoneName:'short'});
console.log( formatterA.format(new Date()) ); // 5/2/2020, EDT

// Get short offset, might show the actual offset but might be a short name
let formatterB = new Intl.DateTimeFormat('en',{timeZone:'America/New_York', timeZoneName:'long'});
console.log( formatterB.format(new Date()) ); // 5/2/2020, Eastern Daylight Time

Another strategy to get the offset is to generate a date in the timezone and get the difference from a UTC date with the same year, month, day, etc. values by parsing the results. It still has the daylight saving boundary issue. The Intl.DateTimeFormat.prototype.formatToParts method helps as for this answer.

However, I suggest you use a library like Luxon as messing with this stuff might do your head in, especially the bit around daylight saving changes.

var DateTime = luxon.DateTime;

let d = DateTime.fromISO("2017-05-15T09:10:23", { zone: "Europe/Paris" });

console.log(d.toFormat('ZZ'));    // +02:00
console.log(d.toFormat('ZZZZZ')); // Central European Summer Time

let e = DateTime.fromISO("2017-05-15T09:10:23", { zone: "Pacific/Kiritimati" });

console.log(e.toFormat('ZZ'));    // +14:00
console.log(e.toFormat('ZZZZZ')); // Line Islands Time 
<script src="https://cdn.jsdelivr.net/npm/luxon@1.23.0/build/global/luxon.min.js"></script>


来源:https://stackoverflow.com/questions/61565813/get-current-gmt-offset-from-a-timezone-identifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!