【问题标题】:How to be sure that Date.today is in Pacific Time Zone?如何确定 Date.today 在太平洋时区?
【发布时间】:2013-03-13 12:05:00
【问题描述】:

我正在跟踪用户活动:

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

#application.rb
config.time_zone = 'UTC'

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

【问题讨论】:

    标签: ruby-on-rails ruby date datetime timezone


    【解决方案1】:

    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,您可以使用帮助程序在您希望的任何时区显示值

    另见:

    【讨论】:

    • 嗯,如果我将日期存储为String 在我的数据库中,格式为:“2012-02-02”比:(Date.today.to_time + Time.zone_offset('PST')).to_date.to_s 更好,因为我将它作为键存储在 Redis 中名称
    • a 字符串是一个字符串,所以我猜它可以工作,这使得以后很难对数据运行查询 - 字符串代码的变体将是 value = Time.use_zone('Pacific Time (US &amp; Canada)') { Time.zone.now.to_date }.to_s,是不是更好,不太确定
    • Date.current 是 Date.today 的 Time.zone 感知版本
    • 棒极了,每天都能学到新东西 - api.rubyonrails.org/classes/Date.html#method-c-current
    【解决方案2】:

    用这种方式替换config.time_zone:

    config.time_zone = 'PST'
    

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

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

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

    【讨论】:

    • 我不想设置这个一般只用于跟踪。
    • Date.today + Time.zone_offset('PST') => Thu, 17 May 1934
    • Date.today.to_time + Time.zone_offset('PST') =&gt; 2013-03-22 16:00:00 +0000
    猜你喜欢
    • 2017-01-29
    • 2015-12-31
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 2015-01-22
    相关资源
    最近更新 更多