显示日期时使 Rails 忽略夏令时

Chr*_*ker 6 ruby datetime ruby-on-rails dst

我在我的 Rails 应用程序中有一个以 UTC 格式存储的日期,并试图将它显示给具有"Eastern Time (US & Canada)"时区的用户。问题是 rails 不断将其转换为东部夏令时 (EDT),因此午夜显示为8am,而应该是7am。有没有办法阻止夏令时转换?

>> time = DateTime.parse("2013-08-26T00:00:00Z")
=> Mon, 26 Aug 2013 00:00:00 +0000 
>> time.in_time_zone("Eastern Time (US & Canada)")
=> Sun, 25 Aug 2013 20:00:00 EDT -04:00
Run Code Online (Sandbox Code Playgroud)

更新

我最终对 @zeantsoi 的方法有所改变。我不太喜欢添加太多的 rails helper,所以我扩展了 active support 的TimeWithZone类。

class ActiveSupport::TimeWithZone
  def no_dst
    if self.dst?
      self - 1.hour
    else
      self
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

现在我可以做 time.in_time_zone("Eastern Time (US & Canada)").no_dst

zea*_*soi 2

创建一个帮助器,利用dst?on 方法TimeZone检查传递的时区当前是否处于 DST。如果是,则从提供的DateTime实例中减去一个小时:

# helper function
module TimeConversion
  def no_dst(datetime, timezone)
    Time.zone = timezone

    if Time.zone.now.dst?
        return datetime - 1.hour
    end

    return datetime
  end
end
Run Code Online (Sandbox Code Playgroud)

然后,在您的视图中渲染调整后(或未调整)的时间:

# in your view
<%= no_dst(DateTime.parse("2013-08-26T00:00:00Z"), 'Eastern Time (US & Canada)') %>
#=> Sun, 25 Aug 2013 19:00:00 EDT -04:00
Run Code Online (Sandbox Code Playgroud)