I'm trying to create a created_at query range that will capture all records created from midnight UTC (db default) to now. In the past I've been able to query for time ranges with:
created_at => (24.hours.ago..Time.now)
But adjusting the above for the new use case does not work:
created_at => (Date.today..Time.now)
Any suggestions on how I can update the created_at range to be all records today / not in the last 24 hours?
Thanks
created_at => (DateTime.now.at_beginning_of_day.utc..Time.now.utc)
I think, you can try for below line as well.
ModelName.all :condition => ["DATE(created_at) = DATE(?)", Time.now]
OR In Rails 3
Model.where "DATE(created_at) = DATE(?)", Time.now
Cheers!
I think time zone should be considered.
where(:created_at => Time.zone.now.beginning_of_day.utc..Time.zone.now.end_of_day.utc)
And Rails will change time to utc time automatically, so the following is also ok.
where(:created_at => Time.now.beginning_of_day..Time.now.end_of_day)
Since Rails5.1, A new method Date#all_day
was introduced, which returns a range of a day
.
Instead of:
where(created_at: Date.today.beginning_of_day..Date.today.end_of_day)
An elegant way is:
where(created_at: Date.today.all_day)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With