使Rails在显示日期时忽略夏令时 [英] Make Rails ignore daylight saving time when displaying a date

查看:117
本文介绍了使Rails在显示日期时忽略夏令时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Rails应用中存储了UTC的日期,并尝试将其显示给具有Eastern Time(US& Canada)的用户时区。问题是,导轨会将其转换为 Eastern Daylight Time(EDT),因此午夜将在上午8点时显示为早上7点。有没有防止DST转换?

I have a date stored in UTC in my Rails app and am trying to display it to a user who has "Eastern Time (US & Canada)" as their timezone. The problem is that rails keeps converting it to Eastern Daylight Time (EDT) so midnight is being displayed as 8am when it should be 7am. Is there anyway to prevent the DST conversion?

>> 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



更新



我最终以@zeantsoi的做法扭转了一切。我不是添加太多导轨助手的巨大粉丝,所以我扩展了主动支持的 TimeWithZone 类。

class ActiveSupport::TimeWithZone
  def no_dst
    if self.dst?
      self - 1.hour
    else
      self
    end
  end
end

现在我可以执行 time.in_time_zone(Eastern Time(US& Canada))。no_dst

推荐答案

创建一个使用时间方向 c> cst =nofollow> dst?以检查传递的时区当前是否处于DST。如果是,则从提供的 DateTime 实例中减去一个小时:

Create a helper that utilizes the dst? method on TimeZone to check whether the passed timezone is currently in DST. If it is, then subtract an hour from the supplied DateTime instance:

# 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

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

Then, render the adjusted (or non-adjusted) time in your view:

# 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

这篇关于使Rails在显示日期时忽略夏令时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆