views:

1078

answers:

2

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 DateTime.now or Time.now but how can I convert that into the format mysql likes?

Thanks

+5  A: 

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

Time.now.to_s(:db)

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.

Time.now.utc.to_s(:db)

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

ryanb
thanks. its awesome to have the railscasts guy answer your questions :)
+2  A: 

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 > ?", Time.now - 1.day])

Rails will automatically convert the timestamp into the correct format.

levinalex
thanks for the response but this doesn't fit my use case. I already have my object retrieved from the DB. Long after it is retrieved, I need to run a time-based validation on it so the check has to be done in Ruby code and not in a query. Thanks again though.
I had a different scenario, and this worked perfectly. Thanks.
aronchick