Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing time and datetime in Ruby on Rails?

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?

like image 726
The Wizard Avatar asked Nov 22 '25 05:11

The Wizard


2 Answers

You can achieve this by doing following:

Post.where("TIME_FORMAT(created_at, '%H:%i:%s') <= ?", time.strftime("%H:%M:%S"))
like image 86
Vrushali Pawar Avatar answered Nov 24 '25 18:11

Vrushali Pawar


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"))
like image 39
usmanali Avatar answered Nov 24 '25 18:11

usmanali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!