为什么 ActiveRecord 对象 return DateTime.now 不同于 DateTime.now
Why does an ActiveRecord object return DateTime.now differently than DateTime.now
假设我有一个简单的 ActiveRecord 模型和这个示例模式:
create_table "users", id: :serial do |t|
t.datetime "updated_at"
end
当我在控制台中运行以下代码时:
user = User.new
user.updated_at = DateTime.now
user.updated_at # => Thu, 27 Feb 2020 09:28:51 GMT +00:00
我的问题是:为什么这个输出与 DateTime.now
的正常 return 值不同,即
DateTime.now # => Thu, 27 Feb 2020 10:28:51 +0100
是否涉及某种序列化程序?我怎样才能找到更多相关信息?
AR updated_at/created_at 是时区感知属性。您可以在这里阅读更多关于它们的信息:
https://api.rubyonrails.org/classes/ActiveRecord/Timestamp.html
例如,如果您获取用户记录,并对其调用 time_zone_aware_types
,您将获得时区感知列类型
user = User.first
user.time_zone_aware_types
=> [:datetime, :time]
这些类型的列在从数据库中检索时会自动转换为 Time.zone
,即使它们是以 UTC 格式存储的。
与 DateTime.now
的区别在于它不识别时区,只是 returns UTC 时间
在
内的 config/application.rb 添加你的时区
class Application < Rails::Application
.......
# it will be like this
config.time_zone = "Asia/Riyadh"
.....
end
假设我有一个简单的 ActiveRecord 模型和这个示例模式:
create_table "users", id: :serial do |t|
t.datetime "updated_at"
end
当我在控制台中运行以下代码时:
user = User.new
user.updated_at = DateTime.now
user.updated_at # => Thu, 27 Feb 2020 09:28:51 GMT +00:00
我的问题是:为什么这个输出与 DateTime.now
的正常 return 值不同,即
DateTime.now # => Thu, 27 Feb 2020 10:28:51 +0100
是否涉及某种序列化程序?我怎样才能找到更多相关信息?
AR updated_at/created_at 是时区感知属性。您可以在这里阅读更多关于它们的信息:
https://api.rubyonrails.org/classes/ActiveRecord/Timestamp.html
例如,如果您获取用户记录,并对其调用 time_zone_aware_types
,您将获得时区感知列类型
user = User.first
user.time_zone_aware_types
=> [:datetime, :time]
这些类型的列在从数据库中检索时会自动转换为 Time.zone
,即使它们是以 UTC 格式存储的。
与 DateTime.now
的区别在于它不识别时区,只是 returns UTC 时间
在
内的 config/application.rb 添加你的时区class Application < Rails::Application
.......
# it will be like this
config.time_zone = "Asia/Riyadh"
.....
end