时区与铁轨3

Add*_*ddy 28 timezone ruby-on-rails ruby-on-rails-3

我有相当普遍的问题,但由于某种原因,我已经尝试了网上的所有建议,似乎没有任何工作.

我已将配置中的时区设置为'EST'

config.time_zone = 'Eastern Time (US & Canada)'
Run Code Online (Sandbox Code Playgroud)

但是当屏幕上显示时间时,它会继续显示存储在数据库中的UTC时间.我尝试了调试器,这是输出

(rdb:1) Time.zone 
#<ActiveSupport::TimeZone:0x1061f4760 @utc_offset=nil, @current_period=nil, @name="Eastern Time (US & Canada)", @tzinfo=#<TZInfo::TimezoneProxy: America/New_York>>
(rdb:1) Order.first.placed_at
Fri Jan 01 15:00:00 UTC 2010
Run Code Online (Sandbox Code Playgroud)

更新:这是另一个具有相同问题的用户 显示时Rails时区错误

Pau*_*ber 36

试试in_time_zone.例如

>> Time.now
=> Sun Dec 05 21:34:45 -0500 2010
>> Time.zone
=> #<ActiveSupport::TimeZone:0x1033d97b8 @name="Pacific Time (US & Canada)", @tzinfo=#<TZInfo::DataTimezone: America/Los_Angeles>, @utc_offset=-28800, @current_period=nil>
>> Time.now.in_time_zone
=> Sun, 05 Dec 2010 18:34:54 PST -08:00
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你想要Order.first.placed_at.in_time_zone.

  • 负.调用它的正确方法是Time.current.我遇到了同样的问题,使用#current代替#now来获取给定时区的时间. (7认同)
  • 但我认为在配置中设置时区会自动指示activerecord在本地时区检索.. http://ryandaigle.com/articles/2008/1/25/what-s-new-in-edge-rails-easier-时区 (4认同)
  • 甚至`Time.zone.now`这似乎对我来说都是一样的(rails 3.1),我认为读得稍微好一些 (3认同)

Dan*_*nny 11

如果要为应用的不同用户设置不同的时区,请确保使用around_filter而不是之前的过滤器来更改Time.zone.与Time.zone如何泄漏到其他线程有关,因此其他用户可能会拥有一个他们不应该的时区.从这篇博客文章:http://ilikestuffblog.com/2011/02/03/how-to-set-a-time-zone-for-each-request-in-rails/

在application_controller.rb中:

around_filter :set_time_zone

private

def set_time_zone
  old_time_zone = Time.zone
  Time.zone = current_user.time_zone if logged_in?
  yield
ensure
  Time.zone = old_time_zone
end
Run Code Online (Sandbox Code Playgroud)

我还发现在允许用户更改时区时使用time_zone_select表单助手方法很有帮助.如果你调用了你的字段:time_zone,你可以使用它:

f.time_zone_select(:time_zone)
Run Code Online (Sandbox Code Playgroud)

最后,这看起来非常棒. 通过javascript自动检测并设置时区.这是添加到资产管道的rails gem:https://github.com/scottwater/detect_timezone_rails和随附的博客文章:http://www.scottw.com/automated-timezone-detection