【问题标题】:Converting System Date to Local Date in Rails在 Rails 中将系统日期转换为本地日期
【发布时间】:2013-05-07 02:09:58
【问题描述】:

我有一个具有此范围的模型:

scope :next_week, lambda { where("date > (?) and date <= (?)", Date.today, Date.today + 1.weeks ) }

但是,它更改日期对我来说太早了,因为我希望应用程序的时间为(并且服务器在 UTC):

config.time_zone = 'Eastern Time (US & Canada)'

我已经看到有关使用 in_time_zone 将 Time.now 转换为配置时间的帖子。

Why doesn't `config.time_zone` seem to do anything?

约会有类似的东西吗?或者有人可以推荐一种方法来调整我的日期查询以将Date.today 计算为本地日期?谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    因为 Date 根本不考虑时区,所以您需要使用 Rails 添加到 Ruby Date 对象的 #to_time_in_current_zone 方法。

    来自文档:

    Converts Date to a TimeWithZone in the current zone if Time.zone or Time.zone_default is set, otherwise converts Date to a Time via #to_time
    

    用法如下:

    Date.today
    # => Mon, 06 May 2013 
    
    Date.today.to_time_in_current_zone
    # => Mon, 06 May 2013 00:00:00 CDT -05:00 
    

    在 Elabs 上 Working with time zones in Ruby on Rails 上有一篇精彩的博文,提供了有关该主题的更多重要信息。

    【讨论】:

    • 谢谢丹。我试过Date.today.to_time_in_current_zone,但它回来了Tue, 07 May 2013 00:00:00 EDT -04:00,即使它仍然是美国东部标准时间的5月6日。链接页面上的信息很好,但是 cmets 中也有讨论暗示Date.today.to_time_in_current_zone 没有按预期更改日期。
    【解决方案2】:

    我通过使用Time.current.to_date 而不是Date.today 解决了这个问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 2017-07-15
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多