【问题标题】:Time zones in rails are really confusing me铁路中的时区真的让我很困惑
【发布时间】:2013-06-27 01:07:27
【问题描述】:

我正在提取每小时数据,将其缓存,然后在 javascript 滚动条中使用该数据。无论如何。这是主要问题。我正在使用:

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

好的看起来不错,当我这样做时:

Entry.first.created_at #datetime -0500

看起来不错,但不是在我使用以下范围时

  scope :hourly, lambda {|h|
    g = DateTime.current.beginning_of_day + h.hours
    where(created_at: g..g+1.hours)
  }
  scope :hourly_by_date, lambda {|h,date|
    g = DateTime.parse(date + " 00:00:00 Eastern Time (US & Canada)") + h.hours
    where(created_at: g..g+1.hours)
  }
  scope :hours_ago, lambda {|h|
    g = DateTime.current.beginning_of_hour - h.hours
    where(created_at: g..g+1.hours)
  }

当我在下午 6:06 (-0700) 创建记录时,它显示的内容表明它是在午夜之前/之后创建的 这太令人沮丧了,我可以使用一些指导。

谢谢。

【问题讨论】:

  • 不要发帖生气。它只会让你看起来像一只鹅:-)
  • 如果你改变y.hours.since(x)而不是x + y.hours(无论你有x + y.hours),它是否有效? AFAIK,+ 不做时区,#since 做。我可能错了……
  • 问题不在于我的 + hours 不起作用,它确实起作用。但是当生成 sql 查询时,与使用 UTC 的数据库相比,它使用了错误的日期/时间。

标签: ruby-on-rails time timezone


【解决方案1】:

您如何将您的日期时间转换为 utc 并将值与数据库进行比较

 scope :hourly, lambda {|h|
    g = (DateTime.current.beginning_of_day + h.hours).utc
    where(created_at: g..g+1.hours)
  }
  scope :hourly_by_date, lambda {|h,date|
    g = (DateTime.parse(date + " 00:00:00 Eastern Time (US & Canada)") + h.hours).utc
    where(created_at: g..g+1.hours)
  }
  scope :hours_ago, lambda {|h|
    g = (DateTime.current.beginning_of_hour - h.hours).utc
    where(created_at: g..g+1.hours)
  }

【讨论】:

  • 将范围设置为 UTC 似乎有助于它现在由于 DST 仅休息 1 小时(Rails 说我的服务器/站点在 MDT 中,而我在亚利桑那州并且它在 MST 中)。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多