Reputation: 908
I've been bashing my head up against timezones in Rails for some time. Here is the issue:
I want users to be able to input into a time_select
field a local time (e.g. 9:30AM). Based on the user's selected time zone, this should be stored in the database as UTC (e.g. 9:30AM EST is saved as 14:30)
Then it's only a matter of using Time.zone
to display it correctly.
However, it seems that time_select
creates a hash of multi-parameter assignment values that assumes that the time the user inputted is in UTC. No matter what I try I cannot coerce it into the user's local time. For example:
ruby-1.9.2-p290 :016 > Time.use_zone("Eastern Time (US & Canada)") do
ruby-1.9.2-p290 :017 > a.attributes = {"starttime(1i)"=>"2000", "starttime(2i)"=>"1", "starttime(3i)"=>"1", "starttime(4i)"=>"09", "starttime(5i)"=>"30"}
ruby-1.9.2-p290 :018?> end
=> {"starttime(1i)"=>"2000", "starttime(2i)"=>"1", "starttime(3i)"=>"1", "starttime(4i)"=>"09", "starttime(5i)"=>"30"}
ruby-1.9.2-p290 :019 > a.starttime
=> 2000-01-01 09:30:00 UTC
I've seen recommendations to use config.time_zone
, but I want this to work for users across multiple time zones, so a site-wide configuration setting doesn't seem like the right solution.
How can I save the user-supplied value in the database as UTC?
Thanks!
Upvotes: 2
Views: 854
Reputation: 4054
Take a look at http://archives.ryandaigle.com/articles/2008/1/25/what-s-new-in-edge-rails-easier-timezones
It covers the use of filters to set timezones for users. You should be able to work in the output from your existing view to set a property on the user's profile (which can then be loaded in the filter).
Upvotes: 1
Reputation: 1598
The following Railscasts episode is great for explaining how to do this if you're a pro member:
http://railscasts.com/episodes/106-time-zones-revised
It basically uses the same approach as Ben W's approach, but uses an around filter instead of a before filter. Its possible that Time.zone is thread-safe, so this could be unneccesary, but I would do it anyway.
Upvotes: 1