什么时候应该在 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.zoneconfig.time_zone 时返回 Time.zone.now,否则只返回时间。

日期时间.当前

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

最新更新