views:

231

answers:

1

Rails is great that it will support timezone overall in the application with Time.zone. I need to be able to support the timezone a user selects for a record. The user will be able to select date, time, and timezone for the record and I would like all calculations to be done with respect to the user selected timezone.

My question is what is the best practice to handle user selected timezones. The model is using a time_zone_select and datetime_select for two different attributes timezone and scheduled_at. When the model saves, the scheduled_at attribute gets converted to the locally defined Time.zone.

When a user goes back to edit the scheduled_at attribute with the datetime_select the datetime is set to the converted Time.zone timezone and not the timezone attribute. Is there a nice way to handle to the conversion to the user selected timezone?

A: 

You could handle this in a before_filter, either in the specified controller or application wide. See this example:

# controllers/application.rb
before_filter :set_user_time_zone

private

def set_user_time_zone
  Time.zone = current_user.timezone if logged_in?
end

Ryan Bates made a screencast about this: Time Zones in Rails 2.1

mikezter
I appreciate the feedback. This is far from what I am looking for though as I am not trying to do it on a pure user level.What I think I need to do is have two timestamps, one that represents the user selected time and timezone and the other as the UTC version.
jtarchie
I would not recommend that, since that will tend to cause confusion on what timestamp represents what time. It's best to default to UTC for storing timestamps and converting them back and forth on display/update. ActiveRecord manages that for you.
mikezter