给定一个tzInfo TimeZone对象(如'America/New_York),‘我如何才能得到相关的国家(国家?)是否会使用带有此标识符的时区?
实例方法不链接回国家:
http://www.rubydoc.info/gems/tzinfo/TZInfo/Timezone
我的问题描述:
发布于 2017-08-08 13:27:48
我不确定是否有直接的方法,但您可以使用 class构建一个哈希,将区域名称映射到国家名。
您可以循环遍历各个国家(使用all方法),并获取每个国家的区域标识符(使用zone_identifiers方法)来构建哈希。
我不经常用Ruby编写代码,所以它可能不是最好的Ruby风格的代码,但是它是这样的:
# 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
endztc将包含区域名称作为键,以及相应国家名称的数组作为值。在我的机器里,我有:
{"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)"],
....提醒您,它只包含与国家相关的时区(格式为Region/City的时区,如Europe/London或America/New_York)。因此,像GMT或Etc/GMT+1这样的名字不会出现在这个列表中。
发布于 2017-08-08 21:01:20
基于@Hugo的回答,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
endhttps://stackoverflow.com/questions/45568483
复制相似问题