什么时候应该在 Rails 中使用“DateTime.now.utc"和“Time.current.utc"? [英] When should `DateTime.now.utc` vs. `Time.current.utc` be used in Rails?
问题描述
在 Rails 中,我对何时使用 DateTime.now.utc 和 Time.current 之间的指导有些困惑.框架内部似乎对哪个最好存在不同意见,尤其是在不同版本中.
In Rails, I'm a little confused on the guidance between when to use DateTime.now.utc and Time.current. There seem to be differing opinions inside the framework about which is best, particularly in different versions.
看起来 DateTime.now.utc
产生一个 UTC 偏移量为零的时间戳,而 Time.current.utc
产生一个时区为 UTC 的时间戳.这似乎是一个微妙的区别,但在许多情况下(例如 DST 计算)非常重要.
It looks like DateTime.now.utc
produces a timestamp with a UTC offset of zero, while Time.current.utc
produces a timestamp with a time zone of UTC. That seems like a subtle distinction but it's pretty important in many cases (e.g. DST calculations).
什么时候应该使用DateTime.now.utc
,什么时候应该使用Time.current.utc
?是否有任何理由使用 DateTime.now.utc
而不是 Time.current.utc
?
When should you use DateTime.now.utc
, and when should you use Time.current.utc
? Is there any reason to use DateTime.now.utc
instead of Time.current.utc
?
推荐答案
我认为你应该使用 .current
而不是 .now
.
I think you should use .current
instead of .now
.
.current
和 .now
的区别在于 .now
使用服务器的时区,而 .current
使用 Rails 环境的设置.如果未设置,则 .current
将与 .now
相同.
The difference of .current
and .now
is .now
use the server's timezone, while .current
use what the Rails environment is set to. If it's not set, then .current
will be same as .now
.
当前时间
在设置 Time.zone 或 config.time_zone 时返回 Time.zone.now,否则只返回Time.now.
Returns Time.zone.now when Time.zone or config.time_zone are set, otherwise just returns Time.now.
DateTime.current
在 Time.zone 或 config.time_zone 时返回 Time.zone.now.to_datetime已设置,否则返回 Time.now.to_datetime.
Returns Time.zone.now.to_datetime when Time.zone or config.time_zone are set, otherwise returns Time.now.to_datetime.
这篇关于什么时候应该在 Rails 中使用“DateTime.now.utc"和“Time.current.utc"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!