【问题标题】:From where Rails take their DateTime.now?Rails 从哪里获取他们的 DateTime.now?
【发布时间】:2018-10-29 09:27:39
【问题描述】:

最近想改updated_at一栏的帖子,可没那么简单!

不过,服务器时间是 12:06,当我使用控制台 (irb) 时,它是 12:06 也试过了:

irb(main):001:0> Time.zone.to_s
=> "(GMT+03:00) Moscow"

当我这样做的时候:

post.update!(updated_at: DateTime.now)
=> true

如果我检索记录,结果是“2018-10-29 09:06:47”

感谢任何帮助!

【问题讨论】:

  • 你的 application.rb 文件中设置了什么时区?
  • 有点过时,但在 Rails 中仍然是一篇不错的文章:robots.thoughtbot.com/its-about-time-zones
  • @Vishal config.time_zone = '莫斯科' config.active_record.default_timezone = :local
  • @jdno 好文章!非常感谢!

标签: ruby-on-rails datetime


【解决方案1】:

尝试使用DateTime.current - 如果您的应用程序在一体机中运行,它将获得分区时间。

来自文档:

在设置 Time.zone 或 config.time_zone 时返回 Time.zone.now.to_datetime,否则返回 Time.now.to_datetime。

基本上,如果您使用时区,Time.zone 应该反映 DateTime.current,而 Time.nowDateTime.now 将忽略任何时区。该方法的来源在这里很容易解释:

def current
  ::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
end

希望对您有所帮助 - 如果您有任何问题,请大声告诉我。

【讨论】:

  • 非常感谢!我很自大地认为now 方法只是current 的更短别名!真丢人!
  • 不客气,尽管我不同意这里的任何傲慢 - 这是一个直接的错误,几周前我自己也犯了一个错误:)
猜你喜欢
  • 2012-11-03
  • 2011-04-16
  • 2014-07-15
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多