简体   繁体   English

DateTime.now还是Time.now?

[英]DateTime.now or Time.now?

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? 在上面( now )的例子中,两者之间是否会有任何差异? (On my current system they are both showing the same time) (在我目前的系统中,他们都显示相同的时间)

Use (Date)Time.current instead of (Date)Time.now 使用(Date)Time.current而不是(Date)Time.now

Rails extends the Time and DateTime objects, and includes the current property 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 not UTC by default. 这很关键 - 除了在用户输入或显示的时区之间进行转换时,您应始终使用UTC时间,但许多生产系统默认不是 UTC。 (eg Heroku is set to PST (GMT -8)) (例如Heroku设置为PST(GMT -8))

See article here 请看这里的文章

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"

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.now and DateTime.now will both return a time in the system's time, which often is set to UTC. Time.nowDateTime.now都将返回系统时间的时间,通常设置为UTC。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM