Time and date comparison in Ruby on Rails?
I find it difficult to compare time and time in rails. I tried to do the following: Post.where("created_at <= ?" time.strftime("%H:%M:%S"))
(Here I am trying to find messages before a specific time of day, regardless of the date).
This does not give the expected result. Is there a way to format created_at on "%H:%M:%S"
when comparing?
source to share
You can do this at the query level. If you are using mysql
, you can follow this link to select the function you want. EXTRACT()
is probably the most suitable for this.
However, if you are using postgresql
, you can refer to this link
Update
Here's an example on how to use it.
Post.where("DATE_FORMAT(created_at,'%H:%M:%S') = ?" time.strftime("%H:%M:%S"))
source to share