Rails 3 user timezones

2019-07-04 05:14发布

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

2条回答
做个烂人
2楼-- · 2019-07-04 05:30

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

查看更多
虎瘦雄心在
3楼-- · 2019-07-04 05:37

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

Invoice.last.created_at.localtime
查看更多
登录 后发表回答