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

Joh*_*lla 15 time ruby-on-rails

在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

xda*_*azz 42

我认为你应该用.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.