何时应该在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.zone或config.time_zone时返回Time.zone.now ,否则只返回Time.now 。
Datetime.current
设置Time.zone或config.time_zone时返回Time.zone.now.to_datetime ,否则返回Time.now.to_datetime 。