Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Timezone with geocode gem?

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?

like image 889
Fran Martinez Avatar asked Dec 20 '22 02:12

Fran Martinez


2 Answers

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
like image 167
Nitin Satish Salunke Avatar answered Dec 31 '22 21:12

Nitin Satish Salunke


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.

like image 39
Daniel Collado-Ruiz Avatar answered Dec 31 '22 22:12

Daniel Collado-Ruiz