Guesstimate timezone from time offset with JavaScript and Moment.js

I know this won't be reliable because the offset is not timezone specific, but with the location data it seems like an educated guess could be made.

Basically, I would like to be able to take an object like this:

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

      

... and return one or more matching time zones, which will be:

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

      

One solution I can think of is to iterate through the zone data provided moment-timezone

, but that just doesn't seem like an elegant way to get this information.

Any ideas?

+3


source to share


2 answers


moment-timezone@0.5.0

added moment.tz.guess()

one that tries to guess the most likely time zone of the user by looking at Date#getTimezoneOffset

and Date#toString

. He then chooses the zone with the largest population. It's not perfect, but it's close enough! Data is retrieved from this table and Intl

used when available.

Fiddle



moment.tz.guess()

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

      

+1


source


It's not very elegant, but iterating through the timezone database allows you to get all the time intervals associated with a given offset.

Note that the time zone database stores the offset change due to daylight saving time rules, as well as the historical evolution of time zones.



Given an offset in minutes, this function returns, according to the iiana timezone database , a list of all timezones that have used this offset once in history or that will use this offset once in a futur.

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

      

+1


source







All Articles