DateTime comparison fails in Rails

2019-04-30 05:35发布

For some reason, the comparison always fail, please check this out from Rails console :

irb(main):021:0> @game.game_date.class
=> ActiveSupport::TimeWithZone
irb(main):026:0> @game.game_date
=> Tue, 19 Feb 2013 23:15:00 UTC +00:00
irb(main):022:0> @game.game_date.to_datetime
=> Tue, 19 Feb 2013 23:15:00 +0000
irb(main):019:0> DateTime.now
=> Tue, 19 Feb 2013 23:48:38 +0330
irb(main):020:0> @game.game_date.to_datetime > DateTime.now
=> true

How come that the comparison is always wrong? I tried this as well:

@game.game_date.to_time > Time.now.to_tim

The result was true as well , while it's obvious that it is supposed to be false since 23:48 > 23:15:00.

Please note that i'm using ruby ruby 1.9.3p0 under ubuntu and Rails 3.1

Any help would be highly appreciated

2条回答
淡お忘
2楼-- · 2019-04-30 05:36

You have a problem with the TimeZone:

irb(main):022:0> @game.game_date.to_datetime
=> Tue, 19 Feb 2013 23:15:00 +0000
irb(main):019:0> DateTime.now
=> Tue, 19 Feb 2013 23:48:38 +0330

You see, your game_date attribute has a +0000 TimeZone, when DateTime.now has a +0330

Try this:

@game.game_date.to_datetime > Time.zone.now
查看更多
干净又极端
3楼-- · 2019-04-30 06:01

It worked to me this way, anyways not sure if it is the best way but at least working the way I'm expecting it :

@game.game_date.to_datetime > Time.now.to_datetime.change(:offset => "+0000") 
查看更多
登录 后发表回答