问题
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
回答1:
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'")
回答2:
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]})
回答3:
How you solve this problem will depend on what database you're using b/c as far as I'm aware there aren't any ActiveRecord
helpers for this type of operation. But there are date functions that should help you figure this out
Postgres Date functions
Mysql Date functions
So for example, in Postgres you might try
extract(hour from timestamp 'a') BETWEEN (extract(hour from timestamp 'b') AND extract(hour from timestamp 'c'))
来源:https://stackoverflow.com/questions/19576109/rails-query-timestamp-between-two-hours