Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query for all records created today (midnight UTC..Now)

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

like image 531
AnApprentice Avatar asked Apr 06 '12 17:04

AnApprentice


4 Answers

created_at => (DateTime.now.at_beginning_of_day.utc..Time.now.utc)
like image 116
Mukesh Avatar answered Oct 12 '22 10:10

Mukesh


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!

like image 32
Manish Shrivastava Avatar answered Oct 12 '22 11:10

Manish Shrivastava


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)

like image 21
yanguango Avatar answered Oct 12 '22 10:10

yanguango


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)
like image 20
Yi Feng Xie Avatar answered Oct 12 '22 10:10

Yi Feng Xie