我正在升级一个庞大,陈旧,笨重的Rails应用程序的Ruby(大多数情况下,我不必在重新格式化的笔记本电脑上重新安装REE)而且我被咬了时区问题非常严重。基本上,从数据库中提取日期时间并没有正确地将它们转换为本地时间:
新系统 - Ruby 2.1.2,Ubuntu 14.04
>> Time.zone.name
=> "Central Time (US & Canada)"
>> ActiveRecord::Base.time_zone_aware_attributes
=> true
>> ActiveRecord::Base.default_timezone
=> :utc
>> Transaction.last.created_at
=> 2014-07-15 02:09:02 UTC
>> Transaction.last.created_at_before_type_cast
=> 2014-07-15 02:09:02 UTC
>> Transaction.last.created_at.localtime
=> 2014-07-14 21:09:02 -0500
>> exit
$ date
Mon Jul 14 22:27:50 CDT 2014
旧系统 - REE,Ubuntu 12.04
>> Transaction.last.created_at
=> Mon, 14 Jul 2014 22:03:11 CDT -05:00
>> Transaction.last.created_at_before_type_cast
=> Tue Jul 15 03:03:11 UTC 2014
>> Transaction.last.created_at.localtime
=> Mon Jul 14 22:03:11 -0500 2014
正如您所看到的,我确保time_zone_aware_attributes
已设置,区域已设置(我在environment.rb中设置),ActiveRecord 存储UTC时间(如预期)。我对此很难过。有人有什么想法吗?
更新
before :all do
@current_tz = Time.zone
Time.zone = 'Pacific Time (US & Canada)'
end
after :all do
Time.zone = @current_tz
end
it 'should report time as Pacific time' do
shift = FactoryGirl.create(:shift)
new_obj = Transaction.create(shift: shift, time: DateTime.new(2013, 3, 31, 0, 0, 0, 0), amount: 0)
new_obj.reload
I18n.localize(new_obj.time, format: :timeonly).should_not == '12:00 am' #We created it with a UTC date, but it should get I18n'd to Pacific time
end
#en.yml
time:
formats:
timeonly: "%l:%M %p"
以上测试也失败。 I18n的东西似乎完全坏了。
更新2
我似乎已将问题隔离到1.9.3 - > 2.1。我想,使用1.9.3很好,我想我会在新服务器上运行它,直到我升级Rails。伤心。我仍然希望听到有关修复的任何建议。
答案 0 :(得分:1)
尝试使用I18n助手来格式化/抵消您的时间输出 - 并强制时区(如果需要)
puts I18n.localize(Transaction.last.created_at, format: :long)
或者
Time.use_zone("Central Time (US & Canada)") do
puts I18n.localize(Transaction.last.created_at, format: :long)
end
我建议您将默认Time.zone
设置为UTC,并根据需要明确更新每个用户 - 这是一篇可能有帮助的博文:http://jessehouse.com/blog/2013/11/15/working-with-timezones-and-ruby-on-rails/