繁体   English   中英

从时区标识符获取当前 GMT 偏移量

[英]Get current GMT offset from a timezone identifier

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

例如:

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

如果它也可以与 ISO 字符串一起使用,那就太好了,例如:

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

您可以使用Intl.DateTimeFormat object 的timeZonetimeZoneName选项来获取更常见的时区的名称,但可能会缺少鲜为人知的时区。 还:

  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方法有助于解决这个问题

但是,我建议您使用像Luxon这样的库,因为弄乱这些东西可能会让您头疼,尤其是在夏令时更改方面。

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM