Kyle Decot
Kyle Decot

Reputation: 20815

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?

Upvotes: 19

Views: 33312

Answers (3)

Ismael
Ismael

Reputation: 16720

@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.

Upvotes: 59

Jenorish
Jenorish

Reputation: 1714

You could use below gem to find the records between dates,

This gem quite easy to use and more clear [By star][1]. I'm using this gem and the API is more clear and the documentation is also well explained.

Post.between_times(
 Time.zone.now - 3.hours,  # all posts in last 3 hours
 Time.zone.now
)

Here you could pass our field also Post.by_month("January", field: :updated_at)

Please see the documentation and try it.

Upvotes: 0

x1a4
x1a4

Reputation: 19485

This looks like it would work, assuming UTC time zone:

Record.where('created_at > ? AND created_at < ?', Date.today + 12.hours, Date.today + 16.5.hours)

or with a BETWEEN:

Record.where('created_at BETWEEN ? AND ?', Date.today + 12.hours, Date.today + 16.5.hours)

BETWEEN may or not may include the second value in the range. Postgres includes it.

Upvotes: 16

Related Questions