Rails 3 user timezones

巧了我就是萌 提交于 2019-12-10 19:34:12

问题


In Rails 2.x I didn't specifically have to set any timezone info and the user, no matter what timezone they were in, would get the datetime specified by the user in their OS.

Now in Rails 3 everything is displayed in UTC. Is it possible to get back that default viewing behaviour without having to put in some js hack to detect the user's timezone?

Thanks!

Chris


回答1:


I found that if you add localtime to your string you get the proper date time...

Invoice.last.created_at.localtime



回答2:


A simple way to lookup the time zone from the IP address:

  require 'open-uri'

  def get_time_zone_from_ip(ip)
    # get external IP of rails server if running on localhost
    ip = open("http://ifconfig.me/ip").string.strip if ip == "127.0.0.1"

    location = open("http://api.hostip.info/get_html.php?ip=#{ip}&position=true")
    if location.string =~ /Latitude: (.+?)\nLongitude: (.+?)\n/
      json = open("http://ws.geonames.org/timezoneJSON?lat=#{$1}&lng=#{$2}")
      geo = ActiveSupport::JSON.decode(json)
      return ActiveSupport::TimeZone::MAPPING.index(geo["timezoneId"]) unless geo.empty?
    end
  end

GeoKit seems like a more robust option for getting the coordinates if you want to look up the coordinates of a postal address.

http://geokit.rubyforge.org/index.html



来源:https://stackoverflow.com/questions/6003491/rails-3-user-timezones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!