Ruby datetime suitable for mysql comparison

Rails has been good with automatically inserting correctly formatted datetimes in MySql without the need for me to give it much thought.

However, for doing a validation, I need to check if a stored mysql datetime value (ie 2008-07-02 18:00:00) is greater than or less than “now”. I can call or but how can I convert that into the format mysql likes?



Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use to_s(:db) to convert into a database friendly format.

However, be careful if you have a timezone specified in Rails because the time will be stored in UTC in the database. You’ll need to specify that to do proper comparisons.

You can also use NOW() function in MySQL instead of generating the current time in Ruby.

Method 2

You don’t need to. Let Rails do the work for you:

If your model is Widget this will find all the widgets that have been created in the last day:

Thing.find(:all, :condition => ["created_at > ?", -])

Rails will automatically convert the timestamp into the correct format.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x