Comparing dates in rails

前端 未结 2 757
终归单人心
终归单人心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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
    

提交回复
热议问题