Comparing DateTime Values ​​in Rails

For some reason, the comparison always fails, please check this from the 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

Why is such a comparison always wrong? I tried this too:

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

The result was true, although it is obvious that it should be false from 23:48> 23:15:00.

Please note that I am using ruby ​​ruby ​​1.9.3p0 under ubuntu and Rails 3.1

Any help would be greatly appreciated

+5
source share
2 answers

You have a problem with 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 +0000TimeZone when DateTime.now has+0330

Try the following:

@game.game_date.to_datetime > Time.zone.now
+7
source

, , , , , , :

@game.game_date.to_datetime > Time.now.to_datetime.change(:offset => "+0000") 
0

All Articles