如何使用地理编码宝石获得时区?

问题描述 投票:3回答:3

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

有没有办法通过这个宝石获得时区?

ruby-on-rails ruby timezone geocode
3个回答
7
投票

您无法直接从地理编码器宝石中获取时区。它可以给你位置。

您可以使用下面的gem来获取特定区域或(纬度,长度)值的时区。

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

1
投票

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

我在这里放的所有代码都是控制器中的方法(在我的例子中,在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替换为您的实际公共IP或类似的东西。我在这里放置了一个IP,以便Geocoder提供的响应与请求中的响应格式相同。

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


0
投票

我已经看到了另一种方法,但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)
© www.soinside.com 2019 - 2024. All rights reserved.