Handling time zones can be a headache for developers, but Rails 2.1 made this process remarkably intuitive. By following a “Global Store, Local View” approach, you can ensure your users always see timestamps that make sense for their specific location.
Here is a simple, step-by-step guide to implementing dynamic time zones.
Step 1: Set Your Application Default
First, you need to establish a baseline. It is a standard industry practice to store all timestamps in UTC (Coordinated Universal Time) in your database. This prevents data corruption when users from different time zones interact.
Open config/environment.rb and add:
config.time_zone = "UTC"
Step 2: Capture the User’s Time Zone
To provide a personalized experience, you need to ask the user for their location. Rails provides a built-in helper to generate a dropdown list of time zones.
In your view file (e.g., edit_profile.rhtml), add the following:
Code snippet
<%= time_zone_select 'user', 'time_zone', TimeZone.all %>
Note: Ensure you have a time_zone string column in your users table to save this selection.
Step 3: Apply the Time Zone Dynamically
Once a user logs in, you need to tell Rails to use their specific preference for that session. You can create a simple method to handle this:
def set_timezone(time_zone)
Time.zone = time_zone
end
Step 4: Ensure Persistence Across the App
To make sure the time zone stays active throughout the user’s session, call the method as soon as the user is authenticated (usually in your ApplicationController via a before_filter):
set_timezone(@logged_in_user.time_zone) if @logged_in_user
Why This Matters
By setting Time.zone dynamically, Rails automatically converts your UTC database timestamps into the user’s local time when rendering views. This keeps your data clean and your users happy.
More to Explore
The Quest for Knowledge Continues. Fuel Your Curiosity.