【问题标题】:How is created_at calculated?created_at 是如何计算的?
【发布时间】:2019-02-03 18:00:43
【问题描述】:

当我创建一个新的 ActiveRecord 实例时,created_at 时间戳被保存到数据库中。

  • 如何计算此时间戳?
  • 时间是否以服务器时间为准?
  • 时间是否始终采用 UTC 时区?
  • 是否有关于此的文档?

【问题讨论】:

  • created_at 是根据服务器的时区保存的。但是,您可以更改时区。是的,默认情况下它是 UTC。
  • @KedarnagMukanahallipatna 感谢您的快速回复,是否有关于此的文档?人们是如何获得这些知识的?
  • 我觉得不是所有东西都在一个地方,关于默认时区是什么以及如何更改,可以看here

标签: ruby-on-rails rails-activerecord utc


【解决方案1】:

这是来自 ActiveRecord 的 _create_record 方法的实现:

def _create_record
  if record_timestamps
    current_time = current_time_from_proper_timezone

    all_timestamp_attributes_in_model.each do |column|
      if !attribute_present?(column)
        _write_attribute(column, current_time)
      end
    end
  end

  super
end

这里是current_time_from_proper_timezone方法的实现:

def current_time_from_proper_timezone
      default_timezone == :utc ? Time.now.utc : Time.now
end
  • 时间戳默认为 UTC(使用 Time.now.utc 计算),但是可以在您的配置中更改它config.active_record.default_timezone = :local(在这种情况下,它将使用 Time.now 计算)

    李>
  • 时间以你的服务器为准

  • 默认为 UTC,但您可以通过设置 config.active_record.default_timezone = :local 来更改它

如果你想看一下代码,这里是链接:https://github.com/rails/rails/blob/master/activerecord/lib/active_record/timestamp.rb

【讨论】:

    猜你喜欢
    • 2020-06-25
    • 2018-12-07
    • 2015-12-09
    • 2011-10-16
    • 2018-11-03
    • 1970-01-01
    • 2021-06-28
    • 2010-11-27
    • 2013-08-17
    相关资源
    最近更新 更多