Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails query between two times

I have a rails app that has a Checkin model. I want to find all records that are within a specific time range for the current day. How would I write a where to get all records that were created between 12PM and 4:30PM?

like image 386
Kyle Decot Avatar asked May 28 '12 02:05

Kyle Decot


Video Answer


1 Answers

@x1a4's answer should be good for you but you can do it in a more readable and shorter way, using a range.

 Checkin.where(created_at: Time.parse("12pm")..Time.parse("4:30pm"))

It should generate something like:

SELECT "checkins".*
FROM "checkins" 
WHERE ("checkins"."created_at" BETWEEN '2012-05-28 12:00:00.000000' AND '2012-05-28 16:30:00.000000')

You can change Time.parse("12pm") with any other way to create a time.

like image 59
Ismael Avatar answered Sep 28 '22 13:09

Ismael