Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime comparison fails in Rails

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

like image 831
Eki Eqbal Avatar asked Feb 19 '13 20:02

Eki Eqbal


1 Answers

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
like image 83
MrYoshiji Avatar answered Oct 05 '22 10:10

MrYoshiji