Comparing dates in rails

2019-01-25 01:49发布

问题:

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.

回答1:

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.



回答2:

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