如何查询今天创建的所有记录(午夜 UTC.现在)



我正在尝试创建一个created_at查询范围,该范围将捕获从午夜UTC(db默认值)到现在创建的所有记录。过去,我已经能够通过以下方式查询时间范围:

created_at => (24.hours.ago..Time.now)

但是针对新用例调整上述内容不起作用:

created_at => (Date.today..Time.now)

关于如何将created_at范围更新为今天/而不是过去 24 小时内的所有记录的任何建议?

谢谢

created_at => (DateTime.now.at_beginning_of_day.utc..Time.now.utc)
我认为

,您也可以尝试以下行。

ModelName.all :condition => ["DATE(created_at) = DATE(?)", Time.now]

或导轨 3

Model.where "DATE(created_at) = DATE(?)", Time.now

干杯!

我认为应该考虑时区。

where(:created_at => Time.zone.now.beginning_of_day.utc..Time.zone.now.end_of_day.utc)

并且 Rails 会自动将时间更改为 UTC 时间,因此以下内容也可以。

where(:created_at => Time.now.beginning_of_day..Time.now.end_of_day)

从 Rails5.1 开始,引入了一个新方法Date#all_day,该方法返回 a range of a day

而不是:

where(created_at: Date.today.beginning_of_day..Date.today.end_of_day)

一个优雅的方式是:

where(created_at: Date.today.all_day)
Date.today.beginning_of_day.utc..Date.today.end_of_day.utc

最新更新