3

I am pretty new in rails, I am facing the following issue, I want to know the client timezone that is accessing my controller. Is there a way to do that? I want to do something like the following code:

client_timezone = request.get_timezones
McSas
  • 2,224
  • 3
  • 27
  • 42
  • Already answered previously: [link]http://stackoverflow.com/questions/338482/can-you-determine-timezone-from-request-variables – RadBrad Aug 24 '12 at 18:04
  • The answers in that question are using js (client side, I need server side) or the maxmind/geoip database (server side), I want to know if there is a gem o a rails way to do the same. – McSas Aug 24 '12 at 18:13

3 Answers3

5

To achieved what I wanted, I used two gems, one called Timezone and another one called GeoCoder. In order to get the timezone in the server side.

With geocoder I can ask for a latitude and longitude of a request and with this piece of information, I use the timezone gem to get the timezone of that coordinate.

Here there are some code:

def my_method
    my_latitude = request.location.latitude
    my_longitude = request.location.longitude
    timezone = Timezone::Zone.new :latlon => [my_latitude, my_longitude]
    timezone_offset = timezone.offset
    ....
end

PS: to use timezone gem you have to create an account in geonames

McSas
  • 2,224
  • 3
  • 27
  • 42
  • Nice approach. I've looked around and found that the alternative to this is using something like https://github.com/kbaum/browser-timezone-rails, which involves using JS that depends on Jquery. – ichigolas Nov 12 '15 at 15:28
2

Well Passed the your time in the cookie and then get the timezone from it

  var offset = (new Date()).getTimezoneOffset()
  var date = new Date();
  date.setTime(date.getTime()+3600000);
  document.cookie = "utc_offset="+offset+"; expires="+date.toGMTString();+"; path=/";

There you have the offset of user timezone with UTC

or Store the User Time zone Information in the databases and then retrieve it

but I guess your requirement is the first one

Good Luck

Viren
  • 5,812
  • 6
  • 45
  • 98
0

While searching for my mini project, I found an alternative API from TimeZoneDB as well.

You can query by latitude & longitude to get the GMT offset, or directly by time zone name.

Sei Kan
  • 79
  • 4