Rails Time zone issue

2019-04-11 11:27发布

Here is my console:

irb(main):048:0> Time.now
=> 2011-04-13 00:51:50 +0200
<c => (@stats[5] == '-' ? 0 : @stats[3]), :earn => @stats[6])
=> #<Reklamer id: 75, virksomhed: "Orville", dato: "2011-04-13 00:00:00", unik_k
lik: 0, klik: 0, unik_vis: 0, vis: 0, leads: 0, ordre: 0, earn: 0, created_at: "
2011-04-12 22:52:13", updated_at: "2011-04-12 22:52:13", cpc: 0>
irb(main):050:0>

As you can see when I create a new item updated_at and created_at is "2011-04-12 22:52:13" instead of the correct time: 2011-04-13 00:51:50

1条回答
狗以群分
2楼-- · 2019-04-11 11:46
irb(main):048:0> Time.now
=> 2011-04-13 00:51:50 +0200
created_at: 2011-04-12 22:52:13 # +0000

Rails stores at +0000 Time zone by default, while your current time zone is +0200

http://railscasts.com/episodes/106-time-zones-in-rails-2-1

Related topics:

UPD

For understanding. If you set config.time_zone = 'Copenhagen' what does it mean?

  • Time will still stored as UTC +0000
  • If you cal @object.created_at (or any other date field) it will offset your time and return your local time.

Example (config.time_zone = 'Moscow' # +0400 )

object = Object.new
object.save
#=> #<Object id: 1, created_at: "2011-04-13 07:46:36", updated_at: "2011-04-13 07:46:36">
object.created_at
#=> Wed, 13 Apr 2011 11:46:36 MSD +04:00

Why does it store Time in +0000 UTC? Because user can choose any local time zone, so it will automaticaly offseted to users time zone.

查看更多
登录 后发表回答