在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
?
答案 0 :(得分:39)
我认为您应该使用.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 。