如何获取请求时区?

时间:2012-08-24 17:52:53

标签: ruby ruby-on-rails-3 timezone

我在rails中很新,我面临以下问题,我想知道正在访问我的控制器的客户端时区。有没有办法做到这一点?我想做类似下面的代码:

client_timezone = request.get_timezones

3 个答案:

答案 0 :(得分:5)

为了达到我的目的,我使用了两个宝石,一个叫Timezone,另一个叫GeoCoder。为了获得服务器端的时区。

使用地理编码器,我可以询问请求的纬度和经度,并使用这条信息,我使用时区gem来获取该坐标的时区。

这里有一些代码:

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:要使用timezone gem,您必须在geonames

中创建一个帐户

答案 1 :(得分:1)

通过你在cookie中的时间,然后从中获取时区

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

您有 UTC

的用户时区偏移量

或将用户时区信息存储在数据库中,然后将其检索

但我猜您的要求是第一个

祝你好运

答案 2 :(得分:0)

在搜索我的迷你项目时,我也从TimeZoneDB找到了另一种API。

您可以按纬度和数字查询获得GMT偏移的经度,或直接time zone name