【问题标题】:Get current GMT offset from a timezone identifier从时区标识符获取当前 GMT 偏移量
【发布时间】:2020-08-17 07:40:54
【问题描述】:

如何从时区标识符中获取当前的 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】:

    您可以使用Intl.DateTimeFormat 对象的timeZone 和timeZoneName 选项来获取更常见的时区名称,但可能会缺少鲜为人知的时区名称.另外:

    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 方法对 this answer 有帮助。

    但是,我建议您使用像 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>

    【讨论】:

    • @yogadog——由内置Date.prototype.toString 生成的字符串在ECMA-262 中定义以包含偏移值,但timezone name string 是实现依赖和可选,名称和偏移量都只在主机时区,所以真的与问题无关。
    猜你喜欢
    • 2015-01-03
    • 2012-11-28
    • 1970-01-01
    • 2019-03-14
    • 2012-08-24
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多