如何确定Date.today在太平洋时区?

tom*_*nek 2 ruby timezone datetime ruby-on-rails date

我正在跟踪用户活动:

def track
   UserActivityTracker.new(date: Date.today.to_s).track
end

#application.rb
config.time_zone = 'UTC'
Run Code Online (Sandbox Code Playgroud)

如何确保在Pacific Time (US & Canada) 时区中跟踪日期.我不想改变时区application.rb

hou*_*se9 5

Rails会使用UTC将数据存储在数据库中(这是一件好事)

我不认为改变config.time_zone现有的应用程序是一个好主意,UTC默认值可能是最好的

当rails使用ActiveRecord从数据库中提取数据时,它将根据Time.zone该请求的设置转换日期时间

Date.today 
# => server time, rails does not convert this (utc on a typical production server, probably local on dev machine)
Time.zone.now.to_date 
# => rails time, based on current Time.zone settings
Run Code Online (Sandbox Code Playgroud)

您可以在ApplicationController上的before_filter中设置当前用户时区,然后在显示日期时使用I18n帮助程序

I18n.localize(user_activity_tracker.date, format: :short)
# => renders the date based on config/locals/en.yml datetime:short, add your own if you wish
# => it automatically offsets from UTC (database) to the current Time.zone set on the rails request 
Run Code Online (Sandbox Code Playgroud)

如果需要显示与当前Time.zone请求设置不同的时间,请使用Time.use_zone

# Logged on user is PST timezone, but we show local time for an event in Central
# Time.zone # => PST
<% Time.use_zone('Central Time (US & Canada)') do %>
  <%= I18n.l(event.start_at, format: :time_only_with_zone) %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

保存数据时,不要打扰进行转换,让rails将其保存为UTC,您可以使用帮助程序在任何时区显示值

也可以看看:

  • Date.current是Date.today的Time.zone感知版本 (2认同)