2009-06-14 114 views
30

假设我有一个标准的Post.first.created_at datetime。我可以比较直接与日期时间格式2009-06-03 16:57:45.608000 -04:00做一样的东西:在rails中比较日期

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

编辑:两个字段都是日期时间没有日期

回答

41

是的,你可以使用比较操作符来比较日期例如: -

irb(main):018:0> yesterday = Date.new(2009,6,13) 
=> #<Date: 4909991/2,0,2299161> 
irb(main):019:0> Date.today > yesterday 
=> true 

但是你想比较的日期为日期时间?

如果是这样,您需要将日期时间转换为日期,然后进行比较。

我希望这会有所帮助。

+3

只是说明:比较轨道自己的日期时间对象与他人可以给出非常意想不到的结果。值得注意的是......见下: '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' 所以你必须这样做......'p.created_at.to_i == p.updated_at.to_i#true' 更多的信息在这里:http:// stackoverflow .COM /问题/ 19599792 /比较-相同,日期时间,对象 - - 红宝石为什么 - 是 - 这些,二,日期时间,NOWS – bwest87 2015-08-28 22:15:06

9

是的,你可以用普通DateTime对象(如一个你可以得到解析你的字符串)直接比较一个created_at ActiveRecord的日期/时间字段的值。

在一个项目中,我有具有created_at DateTime对象值对象:

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 

的created_at字段被定义为:

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

N.B.如果你的领域是一个日期,而不是日期时间,那么你需要将其转换为一个时间:

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

或分析日期:

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

,否则你会得到一个:

ArgumentError: comparison of Date with Time failed