2

我正在跟踪用户活动:

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

#application.rb
config.time_zone = 'UTC'

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

4

2 回答 2

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

您可以在 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 

如果您需要显示与当前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 %>

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

也可以看看:

于 2013-03-23T19:06:06.227 回答
1

config.time_zone以这种方式替换:

config.time_zone = 'PST'

如果您不想更改所有日期,可以使用Time.zone_offset

good_date = bad_date + Time.zone_offset('PST')

您可以在初始化或 before_xxx 回调中添加偏移量。

于 2013-03-23T18:36:58.770 回答