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

问题描述 投票:0回答:1

如何从一个时区标识符中获取当前的GMT偏移量?理想的情况是,它也包括长形式的名称。

比如说:"我的时区标识符是什么?

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

比如说,如果它也能和ISO字符串一起使用就更好了。

2020-12-21T03:57:00Z   //output: GMT-0800 (Pacific Standard Time)
javascript datetime timezone momentjs moment-timezone
1个回答
2
投票

您可以使用 时区时区名 的选择 读取日期时间格式 对象,以获得较常见的时区名称,但可能会遗漏较不知名的时区。另外,在同一个调用中,你不能同时得到它们,所以你需要调用两次。

  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日期的差异。它仍然有夏令时边界的问题。该 读取所有的数据,并将其转换为数据。 方法有助于 本回答.

不过,我建议你使用一个图书馆,比如 卢克逊 因为搞这些东西可能会让你头疼,尤其是夏令时的变化。

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/[email protected]/build/global/luxon.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.