【问题标题】:Rails Time Zone not Setting CorrectlyRails 时区设置不正确
【发布时间】:2020-10-17 10:15:58
【问题描述】:

我正在尝试使用特定于时区的 cron 作业运行一些报告。我读过设置 Time.zone 是一个坏主意,因为它会更改同一线程上其他请求的 Time.zone。我的替代方法是在 Time 对象上使用in_time_zone,但这也会引起问题。我正在尝试查询给定时区的某个开始时间和结束时间之间的记录。但是,当我使用 strptime 然后调用 in_time_zone 时,它完全改变了参考 UTC 的日期。我只想在 CST 度过一天。这是我的代码:

Time.strptime("06/26/2020", "%m/%d/%Y").beginning_of_day #this outputs the beginning of the day in UTC.

Time.strptime("06/26/2020", "%m/%d/%Y").in_time_zone("Central Time (US & Canada)").beginning_of_day #this outputs the 25th at 19:00 hours.

这是我发现在application.rb 之外设置 Time.zone 不是线程安全的链接。

https://rubyinrails.com/2018/02/25/rails-do-not-set-time-zone-to-avoid-time-zone-issues/

【问题讨论】:

  • 阅读 Thoughbot 的 It's About Time (Zones) 为我解决了很多 Rails 时区问题。
  • 当你说“这在 19:00 时输出 25 日”时,你在做什么输出呢?在控制台中是Fri, 26 Jun 2020 00:00:00 CDT -05:00
  • 据我所知,这应该可以解决您的问题:stackoverflow.com/a/15784181/8271939

标签: ruby-on-rails ruby


【解决方案1】:

那些返回不同类的对象。一个是Ruby内置的Time,另一个是Rails的ActiveSupport::TimeWithZone

# Time
Time.strptime("06/26/2020", "%m/%d/%Y").beginning_of_day.class

# ActiveSupport::TimeWithZone
Time.strptime("06/26/2020", "%m/%d/%Y").in_time_zone("Central Time (US & Canada)").beginning_of_day.class

它们也都在 2020 年 6 月 26 日午夜返回,但格式不同(因为它们是不同的班级)和不同的时区。

Time.strptime("06/26/2020", "%m/%d/%Y").beginning_of_day
2020-06-26 00:00:00 -0700

Time.strptime("06/26/2020", "%m/%d/%Y").in_time_zone("Central Time (US & Canada)").beginning_of_day
Fri, 26 Jun 2020 00:00:00 CDT -05:00

虽然它们在本地时钟上的时间相同,但它们是不同的时间点。第一个是 2020 年 6 月 26 日 00:00:00 UTC。第二次是UTC时间2020年6月25日19:00:00。

当您说“这会在 19:00 时输出 25 日”时,可能是因为在显示时间时某些东西正在将其转换回 UTC。在不了解上下文的情况下,这可能是几件事之一。阅读It's About Time (Zones) 会有所帮助。

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 2012-01-16
    • 2023-03-21
    • 2013-04-28
    • 2013-11-16
    • 2016-08-04
    • 2012-01-21
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多