Reputation: 953
I am having difficulty comparing a time and datetime in rails.
I have tried to do the following:
Post.where("created_at <= ?" time.strftime("%H:%M:%S"))
(Here I am trying to find posts before a specific time of the day, regardless of date).
This does not give me the expected result. Is there a way to format created_at to "%H:%M:%S"
when doing the comparison?
Upvotes: 3
Views: 960
Reputation: 2036
You can do it on query level. If you are using mysql
you can follow this link to choose the proper function that you require. EXTRACT()
probably the most suitable for this.
However if you are using postgresql
you can refer to this link
Update:
Here is an example of how to use it.
Post.where("DATE_FORMAT(created_at,'%H:%M:%S') = ?" time.strftime("%H:%M:%S"))
Upvotes: 3
Reputation: 3803
You can achieve this by doing following:
Post.where("TIME_FORMAT(created_at, '%H:%i:%s') <= ?", time.strftime("%H:%M:%S"))
Upvotes: 4