I have to add a time_zone_select
into my Rails application. I was considering some gems to put a default value based on the user request, but I've seen that the project has already installed geocode
gem for this purpose.
Is there any way of get the timezone through this gem?
You cannot get timezone directly from geocoder gem. It can just give you location.
You can use the gem below to get the timezone for a particular 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 be doing the trick for me (for most of the timezones I've tested).
All the code I put here are 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
Of course, you should substitute your.public.ip.here
for your actual public ip, or something similar. I put an IP here so that the response that Geocoder gives has the same format as the one from the request.
I'm happy to hear comments on the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With