Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails query timestamp between two hours

I have a problem in Ruby on Rails, where I need to allow a user to set a two time columns, and then query all instances of that model that have the current time within the hours of the two timestamps. Days do not matter, just within the times specified be the start and end timestamps.

Thanks,

Brian

like image 467
OneChillDude Avatar asked Oct 25 '25 03:10

OneChillDude


2 Answers

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'")
like image 125
Stefan Avatar answered Oct 26 '25 19:10

Stefan


You might be looking for something like

Model.where("starts_at >= ? AND ends_at =< ?", Time.current, Time.current)

Alternatively, you can use placeholder conditions to make the query more concise.

Client.where("created_at >= :start_date AND created_at <= :end_date", {start_date: params[:start_date], end_date: params[:end_date]})

like image 42
Thomas Klemm Avatar answered Oct 26 '25 18:10

Thomas Klemm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!