简体   繁体   English

使用JavaScript和Moment.js从时间偏移猜测时区

[英]Guesstimate time zone from time offset with JavaScript and Moment.js

I know this is not going to be foolproof because an offset isn't specific to a timezone, but with location data it seems like it would be possible to make an educated guess. 我知道这不是万无一失的,因为偏移不是特定于时区,但是对于位置数据,似乎可以进行有根据的猜测。

Basically, I would like to be able to take an object similar to this: 基本上,我希望能够采取类似于此的对象:

{
  offset: -5,
  location: 'America'
}

...and get back either a single or multiple matching time zones, which would be: ...并返回一个或多个匹配的时区,这将是:

['America/Montreal', 'America/New_York', ...]

One solution I can think of is iterating through the zone data provided by moment-timezone , but that just doesn't seem like an elegant way to get this info. 我能想到的一个解决方案是迭代moment-timezone提供的区域数据,但这似乎不是获取此信息的优雅方式。

Any ideas? 有任何想法吗?

It's not really elegant but iterating through the time zone database allows to get all timezones associated with a given offset. 它不是很优雅,但迭代时区数据库允许获得与给定偏移相关联的所有时区。

Note that the timezone database stores the variation of offset due to the daylight saving rules and also the historical evolution of time zones. 请注意,时区数据库存储由于夏令时规则引起的偏移变化以及时区的历史演变。

Given an offset in minutes, this function returns, according to the iana timezone database , the list of all timezones that used this offset once in the history or that will use this offset once in the futur. 给定一个以分钟为单位的偏移量,根据iana时区数据库 ,该函数返回在历史记录中使用此偏移量一次的所有时区的列表,或者将在未来中使用此偏移量一次的所有时区的列表。

function getZonesByOffset(offset){
  //offset in minutes
  results = [];
  var tzNames = moment.tz.names();
  for(var i in tzNames){
    var zone = moment.tz.zone(tzNames[i]);
    for(var j in zone.offsets){
      if(zone.offsets[j] === offset){
        //Add the new timezone only if not already present
        var inside = false;
        for(var k in results){
          if(results[k] === tzNames[i]){
            inside = true;
          }
        }
        if(!inside){
          results.push(tzNames[i]);
        }
      }
    }
  }

moment-timezone@0.5.0 added moment.tz.guess() which attempts to guess the user's most likely timezone by looking at Date#getTimezoneOffset and Date#toString . moment-timezone@0.5.0添加了moment.tz.guess() ,它试图通过查看Date#getTimezoneOffsetDate#toString来猜测用户最可能的时区。 It then picks the zone with the largest population. 然后它选择人口最多的区域。 It's not perfect, but it's close enough! 它并不完美,但足够接近! Data is pulled from this table and Intl is used when available. 该表中提取数据,并在可用时使用Intl

Fiddle 小提琴

moment.tz.guess()

//= America/New_York (I'm in America/Montreal, but this works too)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM