MySQL 适合mysql比较的Ruby datetime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1255983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:50:20  来源:igfitidea点击:

Ruby datetime suitable for mysql comparison

mysqlruby-on-railsrubydatetime

提问by user94154

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

Rails 很擅长在 MySql 中自动插入格式正确的日期时间,而无需我多加考虑。

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.nowor Time.nowbut how can I convert that into the format mysql likes?

但是,为了进行验证,我需要检查存储的 mysql 日期时间值(即 2008-07-02 18:00:00)是否大于或小于“现在”。我可以打电话DateTime.nowTime.now但如何将其转换为 mysql 喜欢的格式?

Thanks

谢谢

回答by ryanb

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

您可以使用to_s(:db)将其转换为数据库友好格式。

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.

但是,如果您在 Rails 中指定了时区,请小心,因为时间将以 UTC 格式存储在数据库中。您需要指定它以进行适当的比较。

Time.now.utc.to_s(:db)

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

您也可以NOW()在 MySQL 中使用函数而不是在 Ruby 中生成当前时间。

回答by levinalex

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

你不需要。让 Rails 为您完成工作:

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

如果您的模型是Widget这将找到在最后一天创建的所有小部件:

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

Rails will automatically convert the timestamp into the correct format.

Rails 会自动将时间戳转换为正确的格式。