How do I get a time zone with a geocode stone?
I need to add time_zone_select
to my Rails application. I've been looking at some gems to put a default based on user request, but I've seen that the project has already installed a geocode
gem for this purpose.
Is there a way to get the timezone through this stone?
You cannot get the time zone directly from the geocoder gem. He can just point you to the location.
You can use the gem below to get the timezone for a specific zone or for (lat, long) values.
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
This seems to do the trick for me (for most time zones I've tested).
All the code I'm putting here is methods in the controller (in my case, in 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
You must of course substitute your.public.ip.here
for your actual public ip or something similar. Here I am putting the IP address so that the response Geocoder gives is in the same format as the request.
I'm glad to hear comments on the code.
I've seen an alternative way to do this, but Nitin Satish's suggestion is still better. Anyway, it's helpful to have more than one option:
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)