Ruby-on-rails – Comparing dates in rails


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.

Best Answer

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

irb(main):018:0> yesterday =,6,13)
=> #<Date: 4909991/2,0,2299161>
irb(main):019:0> > 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.