ruby-on-rails - Rails 应用程序不遵循 config/application.rb 中配置的时区

标签 ruby-on-rails postgresql timezone utc

我是配置时区的新手,对一些要点感到困惑。任何关于正确配置的建议都将不胜感激。

我的理解是,最佳做法是将所有时间戳存储为数据库中的 UTC(我使用的是 PostgreSQL)。另一方面,在实际的应用程序中,我希望看到本地时区 (JST +9:00) 中的时间戳。 我已经像这样配置了 config/application.rb:

module MyApp
  class Application < Rails::Application
    config.load_defaults 5.2
    config.time_zone = 'Tokyo'
  end
end

但是,我不确定它是否配置正确,因为我在 rails console 中得到了混合结果。 Time.zoneTime.now 告诉我时区设置为 JST,但是 created_atupdated_at 时间戳当我执行 User.first 时呈现为 UTC。

User.first
#=> #<User id: 1, first_name: "Bob", last_name: "Smith", created_at: "2019-04-09 08:54:30", updated_at: "2019-04-09 08:54:30"> 

但是,如果我特别要求 created_at 时间,时间将呈现为 JST:

User.first.created_at
#=> Tue, 09 Apr 2019 17:54:30 JST +09:00

除非我特别要求时间本身,否则为什么时间戳会呈现为 UTC?这是正常的吗?我的其他表中的 DateTime 列也发生了同样的现象。

最佳答案

您的所有日期似乎都相同,只是它们在不同上下文中的表示方式而已。

这个:

User.first
#=> #<User id: 1, first_name: "Bob", last_name: "Smith", created_at: "2019-04-09 08:54:30", updated_at: "2019-04-09 08:54:30">

呈现 .inspect 的结果

这个:

User.first.created_at
#=> Tue, 09 Apr 2019 17:54:30 JST +09:00

是控制台猜测您想要使用当前时区格式化日期。

你可以强制某些表示是明确的

User.first.created_at.to_formatted_s(:db) #should print the same as you see on the inspect
I18n.localize(User.first.created_at) #should localize the date with the default date format
I18n.localize(USer.first.created_at, format: :something) #should localize the date as the format you defined as ":something" on your locale file

关于ruby-on-rails - Rails 应用程序不遵循 config/application.rb 中配置的时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55603597/

相关文章:

ruby-on-rails - 在 Ruby on Rails 中从各种文档格式中获取文本

ruby-on-rails - 在 Rails 应用程序中使用 accept_nested_attributes_for 时如何维护嵌套属性的顺序

postgresql - variable_conflict use_variable 是否不能与 UPSERT 的 ON CONFLICT 子句一起使用?

ruby-on-rails - ActiveRecord 和 PostgreSQL : Query jsonb attribute

postgresql - postgres SELECT FOR UPDATE 中的锁定顺序

Django - 无法让时间函数(时区、日期时间)正常工作,获取 ErrorName 消息 : global name not defined

php - PHP,MySQL和时区

python - Python 的 time.time() 是否返回本地或 UTC 时间戳?

ruby-on-rails - Rails 5 安全操作电缆与 redis

ruby-on-rails - Rails 中的用户到用户消息