Rails "config.time_zone" does not apply to datetime data loaded in a text field. Fix?

When I use datetime_select in my form, Rails will correctly adjust the time zone of the date and time data (as configured by config.time_zone ) and display the correctly-zoned time in the edit view of the same form.

But when I try to get the same data in a text box (for the same kind of edit the same form), Rails does not seem to be configured for the time zone.

/events/edit.html.erb(full file):

 <h1>Edit This Event</h1> <%= form_for(@event) do |f| %> <%= render 'fields', :f => f %> <div class="actions"> <%= f.submit "Update Event" %> </div> <% end %> 

/events/_fields.html.erb(only matching lines :)

 <div class="field"> <%= f.label :time_start, "Start Time" %><br /> <%= f.text_field :time_start, :class => "datetimefield" %> </div> 

Example: My zone offset is -500. I entered 8:00 as start_time on the form, 13:00 UTC is written to the database, 8:00 is displayed on the show page (thanks to config.time_zone , which takes into account the offset), but when I try to edit this object, the form text box for start_time will be downloaded from 13:00 (which, if it is sent unchanged, will become 18:00 when it is saved in the database).

This is problematic because I'm trying to use the jQuery UI DatePicker (with the TimePicker add-in) that relies on a text field (will not work with datetime_select ).

Is there a way to make Rails apply the config.time_zone offset to text fields?

Running Rails 3.0.5, deployment to Heroku.

Sorry in advance for asking a very similar question a few weeks ago. The information is still being applied there, I just better understand the problem now, so I asked again.

+8
datetime ruby-on-rails ruby-on-rails-3 forms
source share
2 answers

As I said in this question, the main problem I ran into was that ActiveRecord applied the existing "config.time_zone" setting to the text fields.

It turns out there is a very simple and reliable way to do this: just explicitly add a value: and pull out the exact data - no additional / new methods to call! In my case, it meant:

 <%= f.text_field :time_start, :value => f.object.time_start, :class => "datetimefield" %> 

This was an intermediate step to another potential solution that I was going to try, and I was surprised to find that it worked on its own (again, working with "config.time_zone", which I already installed in 'config / application.rb ').

I tested it and applied the proper DST offset when applicable (as you would expect since "config.time_zone" is set).

+16
source share

How to convert it using TimeZone#utc_to_local ?

Check out the API docs, http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html

+1
source share

All Articles