如何确定两个IANA时区在JavaScript中是否相同?

时间:2019-03-11 21:00:57

标签: javascript timezone

给定两个不同的IANA (aka "tz database" or "Olson") time zones,如何确定它们是否代表相同的区域?

例如,Delivering presents to Eric's house End of ifElse statement ["Eric's house"] Delivering presents to Kenny's house End of ifElse statement ["Kenny's house"] End of ifElse statement ["Eric's house", "Kenny's house"] Delivering presents to Kyle's house End of ifElse statement ["Kyle's house"] Delivering presents to Stan's house End of ifElse statement ["Stan's house"] End of ifElse statement ["Kyle's house", "Stan's house"] End of ifElse statement ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"] i had the doubt like after all the if statement are printed Delivering presents to Eric's house Delivering presents to Kenny's house Delivering presents to Kyle's house Delivering presents to Stan's house and the last ifelse printout gets printed "End of ifElse statement ["Stan's house"]" then the program should come to the end. also there is no while loop present then how does the program print the last 2 statements End of ifElse statement ["Kyle's house", "Stan's house"] End of ifElse statement ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"] Asia/Kolkata代表相同的区域。

另一个示例,Asia/CalcuttaAfrica/Asmara代表相同的区域。

使用detect or guess the user's time zone的API时,这些较小的拼写差异很重要,因为这样一来就无法简单地将字符串与先前存储的值进行比较,因为不同的实现会返回不同的时区标识符。

1 个答案:

答案 0 :(得分:3)

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

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

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