Rails query timestamp between two hours

后端 未结 3 1946
天涯浪人
天涯浪人 2021-01-07 05:33

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 h

3条回答
  •  再見小時候
    2021-01-07 05:46

    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'")
    

提交回复
热议问题