何时应该在Rails中使用`DateTime.now.utc`与`Time.current.utc`?

在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.current

设置Time.zoneconfig.time_zone时返回Time.zone.now ,否则只返回Time.now

Datetime.current

设置Time.zoneconfig.time_zone时返回Time.zone.now.to_datetime ,否则返回Time.now.to_datetime