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?
您可以通过以下方式实现此目的:
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"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.