如何在 JavaScript 中确定两个 IANA 时区是否相同? [英] How to determine if two IANA time zones are the same in JavaScript?

查看:22
本文介绍了如何在 JavaScript 中确定两个 IANA 时区是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个不同的IANA(又名tz 数据库"或Olson")时区,我如何确定它们是否代表相同的区域?

Given two different IANA (aka "tz database" or "Olson") time zones, how can I determine if they represent the same zone?

例如,Asia/KolkataAsia/Calcutta 代表同一个区域.

For example, Asia/Kolkata and Asia/Calcutta represent the same zone.

另一个例子,Africa/AsmaraAfrica/Asmera 代表同一个区域.

Another example, Africa/Asmara and Africa/Asmera represent the same zone.

在使用检测或猜测用户时区的 API 时,这些细微的拼写差异很重要,因为不能简单地将字符串与先前存储的值进行比较,因为不同的实现会返回时区标识符的不同变体.

These minor spelling differences matter when using APIs that detect or guess the user's time zone, as one cannot then simply compare strings to a previously stored value, because different implementations return different variations of the time zone identifier.

推荐答案

完全支持 ECMAScript 国际化 API 的现代 JavaScript 实现,可以使用以下内容:

Modern JavaScript implementations that fully support the ECMAScript Internationalization API, can use the following:

function areSameTimeZones(zone1, zone2) {
  var resolvedZone1 = Intl.DateTimeFormat(undefined, {timeZone: zone1})
                          .resolvedOptions().timeZone;
  var resolvedZone2 = Intl.DateTimeFormat(undefined, {timeZone: zone2})
                          .resolvedOptions().timeZone;
  return resolvedZone1 === resolvedZone2;
}

对于需要与旧浏览器兼容的应用程序,可以利用Moment-Timezone:

For applications requiring compatibility with older browsers, Moment-Timezone can be leveraged:

function areSameTimeZones(zone1, zone2) {
  var z1 = moment.tz.zone(zone1);
  var z2 = moment.tz.zone(zone2);
  return z1.abbrs === z2.abbrs && z1.untils === z2.untils && z1.offsets === z2.offsets;
}

这篇关于如何在 JavaScript 中确定两个 IANA 时区是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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