Accounting for Daylight Savings Time with Rails ActiveSupport::TimeZone
Published September 17, 2015
It's one line of code, and you're certain it's correct.
But then you run it.
THE PROBLEM
A team member had that issue earlier this month. They were trying to write logic to return the hour of the day, but it was always off by one.
THE CODE
irb(main)> ActiveSupport::TimeZone[building.time_zone].utc_offset / 60 / 60=> -6When they ran this, however, the time was five hours off UTC, not six.
They couldn't figure out what was wrong. After "bashing their hands against the keyboard," a colleague realized the issue: daylight savings time (DST).
THE SOLUTION
irb(main)> ActiveSupport::TimeZone[building.time_zone].now.utc_offset / 60 / 60=> -5"If you don't use .now, the ActiveSupport::TimeZone has no concept of what today is or what time it is," They explained. "So without .now, it just returns the standard, non-DST offset."