608.620.5104 | info@tenforward.consulting
Psst! We're hiring!

Our inclusive, feminist office is looking to hire for the following position:

Learn more about the job at our careers page, and learn more about Ten Forward as a company on our mission and vision page and about us page! 

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.  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=> -6

When 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-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," They explained. "So without .now, it just returns the standard, non-DST offset."




FURTHER READING:

Author details

Staff

@TenFwd