如何使用地理编码 gem 获取时区?

How to get Timezone with geocode gem?

我必须将 time_zone_select 添加到我的 Rails 应用程序中。我正在考虑一些 gems 根据用户请求设置默认值,但我看到该项目已经为此目的安装了 geocode gem。

有没有办法通过这个gem获取时区?

您无法直接从地理编码器 gem 获取时区。 它只能给你定位。

您可以使用下面的 gem 获取特定时区或 (lat,long) 值的时区。

https://github.com/panthomakos/timezone

timezone = Timezone::Zone.new :latlon => [-34.92771808058, 138.477041423321]
timezone.zone
=> "Australia/Adelaide"
timezone.time Time.now
=> 2011-02-12 12:02:13 UTC

我看到了另一种方法可以做到这一点,但 Nitin Satish 的建议仍然更好。无论如何,有多个选择是好的:

 loc = request.location.data
 tzc = TZInfo::Country.get(loc["country_code"])
 timezone = Timezone::Zone.new zone:tzc.zone_names.first
 timezone.local_to_utc(Time.now)

这似乎对我有用(对于我测试过的大多数时区)。

我放在这里的所有代码都是控制器中的方法(在我的例子中,在 ApplicationController 中)。

def request_location
  if Rails.env.test? || Rails.env.development?
    Geocoder.search("your.public.ip.here").first
  else
    request.location
  end
end

def get_time_zone
  time_zone = request_location.data["time_zone"]
  return ActiveSupport::TimeZone::MAPPING.key(time_zone) || "UTC"
end

当然,您应该用 your.public.ip.here 代替您实际的 public ip,或类似的东西。我在此处放置了一个 IP,以便 Geocoder 提供的响应与请求中的响应具有相同的格式。

我很高兴听到对代码的评论。