【发布时间】: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