608.620.5104 | info@tenforward.consulting

Accounting for Daylight Saving 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. She was 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=> -6

When she ran this, however, the time was five hours off UTC, not six.

She couldn't figure out what was wrong. After "bashing her hands against the keyboard," a different colleague realized the issue: daylight-saving 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," she explained. "So without .now, it just returns the standard, non-DST offset."




FURTHER READING:

Author details

Staff

@TenFwd