How to determine if two IANA time zones are the same in JavaScript?

问题: Given two different IANA (aka "tz database" or "Olson") time zones, how can I determine if they represent the same zone? For example, Asia/Kolkata and Asia/Calcutta repr...

问题:

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

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

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

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.


回答1:

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;
}

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;
}
  • 发表于 2019-03-13 00:18
  • 阅读 ( 180 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除