Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 554
Tom Lehman Avatar asked Jun 14 '09 08:06

Tom Lehman


2 Answers

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.

like image 78
mechanical_meat Avatar answered Nov 15 '22 20:11

mechanical_meat


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
like image 28
LucaM Avatar answered Nov 15 '22 21:11

LucaM