Rails 3用户时区

3
在 Rails 2.x 中,我不需要特别设置任何时区信息,无论用户处于哪个时区,他们都会得到操作系统中指定的日期时间。

现在在 Rails 3 中,所有内容都以协调世界时(UTC)显示。是否有可能恢复默认的查看行为,而无需插入一些 js 来检测用户的时区?

谢谢!

Chris

2个回答

6
我发现如果您在字符串中添加本地时间,就可以得到正确的日期时间...
Invoice.last.created_at.localtime

4
但这仅与铁轨运行的系统相关。如果您从不同的时区访问它,它仍将显示其所在时区的时间,而不是您的时间。 - Chris A.
哦,那很不幸...那么你有最终的解决方案让它总是能够工作吗? - dmonopoly
我还没有做到那一步,但我想唯一要做的就是为所有用户设置时区或使用一些丑陋的JS hack。 - Chris A.

0

从 IP 地址查找时区的简单方法:

  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似乎是一个更强大的选项。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接