36

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.

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
Tom Lehman
  • 85,973
  • 71
  • 200
  • 272

2 Answers2

52

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.

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
  • 5
    Just a note: Comparing rails own datetime objects against others can give very unexpected results. Notably... see below: `p.created_at # Fri, 28 Aug 2015 21:45:14 UTC +00:00` `p.updated_at # Fri, 28 Aug 2015 21:45:14 UTC +00:00 ` `p.created_at == p.updated_at # false` So you have to do this... `p.created_at.to_i == p.updated_at.to_i # true` more info here: http://stackoverflow.com/questions/19599792/comparing-identical-datetime-objects-in-ruby-why-are-these-two-datetime-nows – bwest87 Aug 28 '15 at 22:15
10

Yes you can compare directly the value of a created_at ActiveRecord date/time field with a regular DateTime object (like the one you can obtain parsing the string you have).

In a project i have a Value object that has a created_at datetime object:

imac:trunk luca$ script/console
Loading development environment (Rails 2.3.2)
>> Value.first.created_at
=> Fri, 12 Jun 2009 08:00:45 CEST 02:00
>> Time.parse("2009-06-03 16:57:45.608000 -04:00")
=> Wed Jun 03 22:57:45 0200 2009
>> Value.first.created_at > Time.parse("2009-06-03 16:57:45.608000 -04:00")
=> true

The created_at field is defined as:

  create_table "values", :force => true do |t|
    [...]
    t.datetime "created_at"
  end

N.B. if your field is a date and not a datetime, then you need to convert it to a time:

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

or parse a date:

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

otherwise you'll get a:

ArgumentError: comparison of Date with Time failed
LucaM
  • 2,856
  • 1
  • 19
  • 11