Comparing dates in rails

Tom Lehman picture Tom Lehman · Jun 14, 2009 · Viewed 72.9k times · Source

Suppose I have a standard Post.first.created_at datetime. Can I compare that directly with a datetime in the format 2009-06-03 16:57:45.608000 -04:00 by doing something like:

Post.first.created_at > Time.parse("2009-06-03 16:57:45.608000 -04:00")

Edit: Both fields are datetimes, not dates.

Answer

mechanical_meat picture mechanical_meat · Jun 14, 2009

Yes, you can use comparison operators to compare dates e.g.:

irb(main):018:0> yesterday = Date.new(2009,6,13)
=> #<Date: 4909991/2,0,2299161>
irb(main):019:0> Date.today > yesterday
=> true

But are you trying to compare a date to a datetime?

If that's the case, you'll want to convert the datetime to a date then do the comparison.

I hope this helps.