在Rails中,我对何时使用DateTime.now.utc和Time.current之间的指导有点困惑。框架内部似乎对哪个最好有不同的意见,尤其是在不同的版本中。
看起来DateTime.now.utc
生成 UTC 偏移量为零的时间戳,而Time.current.utc
生成时区为 UTC 的时间戳。这似乎是一个微妙的区别,但在许多情况下非常重要(例如 DST 计算)。
什么时候应该使用DateTime.now.utc
,什么时候应该使用Time.current.utc
?有什么理由使用DateTime.now.utc
而不是Time.current.utc
吗?
我认为你应该使用.current
而不是.now
。
.current
和.now
的区别在于.now
使用服务器的时区,而.current
使用Rails环境的设置。如果未设置,则.current
将与.now
相同。
时间.当前
当设置了 Time.zone 或 config.time_zone 时返回 Time.zone.now,否则只返回时间。
日期时间.当前
返回Time.zone.now.to_datetime当时区或config.time_zone设置,否则返回Time.now.to_datetime。