Ruby-on-rails DateTime.now 还是 Time.now?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5600667/
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-09-03 00:53:27  来源:igfitidea点击:

DateTime.now or Time.now?

ruby-on-railsrubytimetimezone

提问by Zabba

Which of the two should I be using in my Rails application:

我应该在我的 Rails 应用程序中使用这两个中的哪一个:

DateTime.now or Time.now

Is there any harm in using both in the application?

在应用程序中同时使用两者有什么危害吗?

Can there ever be any differences between the two in case of the above (now) example? (On my current system they are both showing the same time)

在上述 ( now) 示例的情况下,两者之间是否有任何区别?(在我当前的系统上,它们都显示在同一时间)

采纳答案by slandau

In reference to Time.now(not DateTime.now):

关于Time.now(不是DateTime.now):

The object created will be created using the resolution available on your system clock, and so may include fractional seconds.

创建的对象将使用系统时钟上可用的分辨率创建,因此可能包含小数秒。

a = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
b = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
a == b            #=> false
"%.6f" % a.to_f   #=> "1049896563.230740"
"%.6f" % b.to_f   #=> "1049896563.231466"

回答by Yarin

Use (Date)Time.currentinstead of (Date)Time.now

使用(Date)Time.current代替 (Date)Time.now

Rails extends the Timeand DateTimeobjects, and includes the currentproperty for retrieving the time the Rails environment is set to (default = UTC), as opposed to the server time (Could be anything).

Rails 扩展了TimeDateTime对象,并包括current用于检索 Rails 环境设置的时间(默认 = UTC)而不是服务器时间(可以是任何东西)的属性。

This is critical- You should always be working in UTC time except when converting between timezones for user input or display- but many production systems are notUTC by default. (e.g. Heroku is set to PST (GMT -8))

这是至关重要的 - 您应该始终在 UTC 时间工作,除非在时区之间转换以进行用户输入或显示 - 但许多生产系统默认情况下不是UTC。(例如 Heroku 设置为 PST (GMT -8))

See article here

这里的文章

回答by KurtPreston

If you want to get the time in the application's time zone, you'll need to call Time.zone.now, so that's what I generally use.

如果要获取应用程序时区的时间,则需要调用Time.zone.now,这就是我通常使用的方法。

Time.nowand DateTime.nowwill both return a time in the system's time, which often is set to UTC.

Time.now并且DateTime.now都将返回系统时间中的时间,通常设置为 UTC。