如何修复 rails 中与 sqlite 在不同时区检索的时间?

How to fix time retrieved in a different time zone from sqlite in rails?

我通过添加以下内容在 config/application.rb 中设置了默认时区:

config.time_zone = 'Pacific Time (US & Canada)'
config.active_record.default_timezone = :local

尽管 Time.now 显示了正确的时区并且生成的查询在使用 ActiveRecord 检索记录时显示了正确的时区,但我得到了错误的时区。如何解决?

irb(main):010:0> Time.now
=> 2015-01-15 00:17:18 -0800
irb(main):011:0> Article.first.update_attributes(:updated_at => Time.now)
Article Load (0.2ms)  SELECT  "articles".* FROM "articles"  ORDER BY "articles"."id" ASC LIMIT 1
(0.1ms)  begin transaction
SQL (0.3ms)  UPDATE "articles" SET "updated_at" = ? WHERE "articles"."id" = ?  [["updated_at", "2015-01-15 00:17:23.369993"], ["id", 1]]
(4.7ms)  commit transaction
=> true
irb(main):012:0> Article.first
Article Load (0.2ms)  SELECT  "articles".* FROM "articles"  ORDER BY "articles"."id" ASC LIMIT 1
=> #<Article id: 1, title: "First article updated", body: "This is my first article", published_at: "2015-01-14 06:53:00", created_at: "2015-01-14 06:53:38", updated_at: "2015-01-15 08:17:23", excerpt: nil, location: nil>

我觉得你把事情搞砸了。在你的例子中一切都很好。看:

▶ d1 = DateTime.parse "2015-01-15 00:17:18 -0800"
#=> #<DateTime: 2015-01-15T00:17:18-08:00 ((2457038j,29838s,0n),-28800s,2299161j)>
▶ d2 = DateTime.parse "2015-01-15 08:17:18"
#=> #<DateTime: 2015-01-15T08:17:18+00:00 ((2457038j,29838s,0n),+0s,2299161j)>
▶ d1 == d2
#=> true

现在你想要的是获取你所在时区的时间?没有比这更简单的了:

▶ d2.to_time
#=> 2015-01-15 09:17:18 +0100

后者显示+0100只是因为我在CET。您的 to_time 将显示与 Time.new 相同的 TZ。