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

时间:2015-01-15 08:29:48

标签: ruby-on-rails ruby sqlite timezone

我通过添加以下内容在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>

1 个答案:

答案 0 :(得分:1)

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

▶ 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。