35

With Ruby on Rails console, is it possible to query the database for all records created on a certain day?

something like

date = "january 5 2013"
users = User.find(:all, :conditions => {:created_at => date})
Seth
  • 10,198
  • 10
  • 45
  • 68

5 Answers5

86

You can do it like this:

date = Date.parse('january 5 2013')
users = User.where(created_at: date.midnight..date.end_of_day)
Agis
  • 32,639
  • 3
  • 73
  • 81
5

Try this,

User.where("Date(updated_at) = ?", "2018-02-9")
Praveen Kumar
  • 161
  • 1
  • 6
2

You can also do it like

User.where("created_at::date = ?", "january 5 2013".to_date)
M. Habib
  • 623
  • 1
  • 9
  • 15
1

Yes, It is possible like:

date = Date.parse("january 5 2013")
users = User.where(created_at: date)

but created_at is type of date-time like 2014-01-28 08:35:00.9608

and I think All user have different created_at

So you may used like this

User.where("created_at = ?", "2014-01-23 16:19:48.199086")
Adobe
  • 12,967
  • 10
  • 85
  • 126
Dheer
  • 773
  • 1
  • 6
  • 16
  • The first part does not work. Don't you have to convert strings to date? The second part might work, but I need it to be variable. I want all users from that day, not a specific user. – Seth Jan 28 '14 at 17:22
  • You may use stamp gem and use varibale like date = Date.today.stamp("january 5 2013") – Dheer Jan 29 '14 at 06:52
1

If you see the follow link Don't use BETWEEN (especially with timestamps) You will note that you can have problems.

Instead you can use

users = User.where('created_at >= ? and created_at <=?', date.midnight, date.end_of_day)



"SELECT \"users\".* FROM \"users\" WHERE (created_at >= '2018-05-17 07:00:00' and created_at <='2018-05-18 06:59:59.999999')"
poramo
  • 546
  • 5
  • 7