Christopher Oezbek
Christopher Oezbek

Reputation: 26363

Get Country from tzInfo TimeZone?

Given a tzInfo TimeZone object such as 'America/New_York' how can I get the associated country (countries?) that would use the time zone with this identifier?

The instance methods don't link back to countries:

http://www.rubydoc.info/gems/tzinfo/TZInfo/Timezone

My problem description:

Upvotes: 2

Views: 1268

Answers (2)

Christopher Oezbek
Christopher Oezbek

Reputation: 26363

Based on @Hugo's answer, a short extension to class Timezone:

module TZInfo

class Timezone

    def countries
        return Timezone::country_map[self.name] || []
    end

    @@countryMap = nil

    def self.country_map
        if @@countryMap.nil?
          @@countryMap = {}

            TZInfo::Country.all().each do |c|
                c.zone_identifiers.each do |z|
                    @@countryMap[z] ||= [] 
                    @@countryMap[z] << c.name
                end
            end
        end
        return @@countryMap
    end

end

end

Upvotes: 1

user7605325
user7605325

Reputation:

I'm not sure if there's a direct way, but you can use the Country class to build a hash that maps zone names to country names.

You can loop through the countries (using all method) and get the zone identifiers for each country (using zone_identifiers method) to build the hash.

I don't code in Ruby very often, so probably it's not the best Ruby-style code, but it's something like this:

# map zones to countries
ztc = {}

TZInfo::Country.all().each do |c|
  c.zone_identifiers.each do |z|
    ztc[z] = [] unless ztc.has_key?(z)
    ztc[z].push(c.name)
  end
end

ztc will contain the zone names as keys, and an array of the respective country names as values. In my machine, I've got:

{"Europe/Andorra"=>["Andorra"],
 "Asia/Dubai"=>["United Arab Emirates", "Oman"],
 "Asia/Kabul"=>["Afghanistan"],
 "America/Port_of_Spain"=>["Antigua & Barbuda", "Anguilla", "St Barthelemy", "Dominica",
                           "Grenada", "Guadeloupe", "St Kitts & Nevis", "St Lucia",
                           "St Martin (French)", "Montserrat", "Trinidad & Tobago",
                           "St Vincent", "Virgin Islands (UK)", "Virgin Islands (US)"],
  ....

Just reminding that it'll contain only timezones that are associated with countries (the ones with the format Region/City, like Europe/London or America/New_York). So names like GMT or Etc/GMT+1 won't be in that list.

Upvotes: 3

Related Questions