0

I'm trying to run some reports with a cron job that are Timezone specific. I've read that setting Time.zone is a bad idea since it alters the Time.zone for other requests on the same thread. My alternative was to use in_time_zone on a Time object but that is causing issues too. I'm trying to query records between a certain start and end time for a given time zone. However, when I use strptime and then call in_time_zone it completely alters the day in reference to UTC. I simply want the day in CST. Here is my code:

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.

Here is the link I found that stated setting Time.zone outside of the application.rb wasn't thread safe.

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

Cannon Moyer
  • 3,014
  • 3
  • 31
  • 75
  • Reading Thoughbot's [It's About Time (Zones)](https://thoughtbot.com/blog/its-about-time-zones) cleared up a lot of Rails time zone issues for me. – Schwern Jun 26 '20 at 18:59
  • When you say "this outputs the 25th at 19:00 hours", what are you doing to output it? In the console it's `Fri, 26 Jun 2020 00:00:00 CDT -05:00`. – Schwern Jun 26 '20 at 19:03
  • From what I can see, this should solve your issue: https://stackoverflow.com/a/15784181/8271939 – Clemens Kofler Jun 26 '20 at 19:10

1 Answers1

0

Those return objects of different classes. One is the built-in Ruby Time, the other is Rails's 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

They also both return midnight on June 26th, 2020, though in different formats (because they're different classes) and in different time zones.

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

While they are the same time on the local clock, they are different points in time. The first is June 26th, 2020 00:00:00 UTC. The second is June 25th, 2020 19:00:00 UTC.

When you say "this outputs the 25th at 19:00 hours" it is likely because something is converting it back to UTC when it displays the time. Without knowing the context, this could be one of several things. Reading It's About Time (Zones) will help.

Schwern
  • 153,029
  • 25
  • 195
  • 336