Comparing dates in rails

前端 未结 2 748
终归单人心
终归单人心 2020-12-16 09:53

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

相关标签:
2条回答
  • 2020-12-16 10:24

    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.

    0 讨论(0)
  • 2020-12-16 10:29

    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
    
    0 讨论(0)
提交回复
热议问题