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?
You can achieve this by doing following:
Post.where("TIME_FORMAT(created_at, '%H:%i:%s') <= ?", time.strftime("%H:%M:%S"))
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With