从时区标识符获取当前的GMT偏移量 [英] Get current GMT offset from a timezone identifier

查看:81
本文介绍了从时区标识符获取当前的GMT偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从时区标识符获取当前的GMT偏移量?理想情况下,它也应包含长格式名称.

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

例如:

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

如果它也适用于ISO字符串,那就太好了,例如:

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

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

推荐答案

您可以使用timeZone 和 timeZoneName 选项developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat"rel =" nofollow noreferrer> Intl.DateTimeFormat 对象如下所示,以获取更多常见时区的名称,但鲜为人知的可能会丢失.另外:

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. 您不能在一次通话中同时获得这两个电话,因此您需要两次拨打电话
  2. 在某些情况下,您只会得到短名称和长名称而没有实际的偏移量
  3. 时区名称不是标准化的,因此不同的实现可能会返回不同的名称,或者只是不带名称的实际偏移量.
  4. 您将获得所创建的日期和时间的偏移量,而不是位置的日期和时间,因此,如果该差异超出了夏时制边界,则可能是错误的

例如

// 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

获取偏移量的另一种策略是生成时区中的日期,并通过解析结果来获取与具有相同年,月,日等值的UTC日期的差值.它仍然存在夏令时边界问题. Intl.DateTimeFormat.prototype.formatToParts 方法有助于此答案.

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.

但是,我建议您使用 Luxon 之类的库,因为弄乱这些东西可能会使您前进,尤其是夏令时的变化.

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>

这篇关于从时区标识符获取当前的GMT偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆