Ruby datetime适合mysql比较 [英] Ruby datetime suitable for mysql comparison
问题描述
Rails在MySql中自动插入正确格式的数据时间是不错的选择,而无需我多思考。
但是,为了进行验证,我需要检查一个存储的mysql datetime值(即2008-07-02 18:00:00)是否大于或小于比现在。我可以调用 DateTime.now
或 Time.now
,但是如何将它转换成mysql喜欢的格式? p>
谢谢
您可以使用 to_s :db)
转换成数据库友好的格式。
Time.now.to_s(:db )
但是,如果您在Rails中指定了时区,请小心,因为时间将以UTC格式存储在数据库中。您需要指定进行适当的比较。
Time.now.utc.to_s(:db)$ b $您还可以在MySQL中使用 NOW()
函数,而不是使用 $ / pre>
在Ruby中生成当前时间。
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
解决方案 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.
这篇关于Ruby datetime适合mysql比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!