Posted about 3 years ago. Visible to the public. Repeats.

How to Work With Time Zones in Rails

With different time zones

When dealing with time zones in Rails, there is one key fact to keep in mind:

Rails has configurable time zones, while
Ruby is always in the server's time zone

Thus, using Ruby's time API will give you wrong results for different time zones.

For consistency, you should only use Rails' methods, but the hard thing is to know which method originates from Ruby and which from Rails. To simplify this, adhere to the following suggestion:

Use Time.zone for everything time-related

Copy
# Example usage of Time.zone Time.zone.now # instead of Time.now, DateTime.now Time.zone.today # instead of Date.today Time.zone.local(...) # instead of Date.new, DateTime.new Time.zone.at(...) # instead of Time.at Time.zone.parse(...) # instead of Time.parse date.beginning_of_day # instead of date.to_time

Things like 2.hours.ago work as expected, because they're provided by Rails. Still, prefer using Time.zone.now + 2.hours as it will leave no doubt about time zones being respected.

In case you should get time objects without time zone information, you can still turn them into zoned times by calling #in_time_zone, e.g.: Time.now.in_time_zone.

"Without" time zones

You can not actually "disable" time zones, because their existence is a fact. You can, however, tell Rails the only single time zone you'll need is the server's.

Copy
config.time_zone = "Berlin" # Local time zone config.active_record.default_timezone = :local config.active_record.time_zone_aware_attributes = false

Now you may again use both Ruby's and Rails' whole time API.


Reference

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Dominik Schöler
Last edit:
almost 2 years ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more