Rails 3 DateTime Comparison w/ Date In An ActiveRecord Query

前端 未结 4 1339
死守一世寂寞
死守一世寂寞 2021-02-09 00:58

I\'m trying to search a model for any dates equal to a specific date while omitting the timestamp. In Rails I could simply execute this as DateTime.to_date == somedate

4条回答
  •  我寻月下人不归
    2021-02-09 01:42

    DateTime class have two usefull methods to do this: beginning_of_day and end_of_day.

    For this case, in which you have a Date object, you might do:

    Foo.where('created_at >= #{Date.today.to_time.beginning_of_day} AND 
               created_at <= #{Date.today.to_time.end_of_day}')
    

    Notice that you have to transform the Date object to a DateTime object

提交回复
热议问题