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?

+3


source to share


2 answers


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

      

+3


source


You can achieve this by following these steps:



Post.where("TIME_FORMAT(created_at, '%H:%i:%s') <= ?", time.strftime("%H:%M:%S"))

      

+4


source







All Articles