Rails 3个用户时区
在Rails 2.x中,我没有特别设置任何时区信息,用户,无论他们在哪个时区,都会获得用户在其操作系统中指定的日期时间。
现在在Rails 3中,所有内容都以UTC格式显示。 是否有可能恢复默认的查看行为而无需添加一些js hack来检测用户的时区?
谢谢!
克里斯
我发现如果你在你的字符串中添加localtime,你会获得正确的日期时间……
Invoice.last.created_at.localtime
从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似乎是一个更健壮的选项来获取坐标。