Rails 应用不遵循 config/application.rb 中配置的时区
Rails app not following the timezone configured in config/application.rb
我是配置时区的新手,对一些要点感到困惑。任何关于正确配置的建议将不胜感激。
我的理解是最好将所有时间戳存储为数据库中的 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.zone
和 Time.now
告诉我时区设置为 JST,但是 created_at
和 updated_at
时间戳在我 User.first
.[=24 时呈现为 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
我是配置时区的新手,对一些要点感到困惑。任何关于正确配置的建议将不胜感激。
我的理解是最好将所有时间戳存储为数据库中的 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.zone
和 Time.now
告诉我时区设置为 JST,但是 created_at
和 updated_at
时间戳在我 User.first
.[=24 时呈现为 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