Rails Query Timestamp Between Two Hours

Rails query timestamp between two hours

Something like this should work (assuming MySQL):

Model.where("TIME(created_at) BETWEEN '07:00:00' AND '09:00:00'")

You can convert a Time instance to this format with:

Time.now.strftime("%T") #=> "23:02:25"

If the start time is larger than the end time you could reverse the logic, so instead of:

Model.where("TIME(created_at) BETWEEN '23:00:00' AND '01:59:59'")

You could use:

Model.where("TIME(created_at) NOT BETWEEN '02:00:00' AND '22:59:59'")

Rails query timestamp between two hours with postgresql

You can cast created_at to a time (which doesn't include the date) and then use BETWEEN.

#= select * from times;
t
---------------------
2016-01-01 12:00:00
2016-02-02 13:00:00
2016-03-03 14:00:00
2016-04-04 15:00:00
(4 rows)
#= select * from times where t::time between '12:30:00' AND '14:30:00';
t
---------------------
2016-02-02 13:00:00
2016-03-03 14:00:00
(2 rows)

Coming through Rails, that would be:

Review.where("created_at::time BETWEEN '12:30:00' AND '14:30:00'")

Rails query between two times

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

Check if time is between two times ruby

I would use the between?(min, max) function from ActiveSupport:

def closed?
DateTime.now.between?(DateTime.new(2018, 6, 28, 13, 00, 00), DateTime.new(2018, 6, 28, 14, 00, 00))
end

Rails ActiveRecord date between

Just a note that the currently accepted answer is deprecated in Rails 3. You should do this instead:

Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)

Or, if you want to or have to use pure string conditions, you can do:

Comment.where('created_at BETWEEN ? AND ?', @selected_date.beginning_of_day, @selected_date.end_of_day)

How do I search between two times?

From what I understand you're applying a function to extract time from a datetime attribute in your SQL. Something like select HOUR(created_at)...

ActiveRecord can't do that, however the gem squeel does it in Ruby.

Person.select{coalesce(name, '<no name given>')}

But there's nothing fundamentely different than doing it in plain SQL.

Rails ActiveRecord - how to fetch records between two dates

data = ModelName.where("today >= from_date AND today <= to_date")


Related Topics



Leave a reply



Submit