Reputation: 59
I have a form that looks like
= form.datetime_select :due_at
= form.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones
When this object is saved, we need it to apply the time zone that was selected. For example if the user selects "03-01-2013 11:00" and "Central Time (US & Canada)", I want the date/time, in this case 11AM to be as 11AM CST instead of our application default time zone of "Pacific Time (US & Canada)".
This is actually nested within another form so we cannot simply change Time.zone in the controller with an around_filter. We are trying to figure out a solution that works during daylight savings time as well.
Upvotes: 3
Views: 2934
Reputation: 1476
If due_at
and time_zone
are both attributes of a single model, then you could use a before_save hook to make sure due_at
is encoded in the time zone of time_zone
before being stored in the database.
class YourModel < ActiveRecord::Base
before_save :apply_time_zone
protected
def apply_time_zone
self.due_at = ActiveSupport::TimeZone[time_zone].parse "#{due_at_start.to_s(:db)} UTC"
end
end
ActiveSupport::TimeZone[t].parse(s)
will parse s
into time zone t
, and .to_s(:db)
converts a time to string in UTC.
Upvotes: 3