I develop an application in Ruby on Rails 4 with TimeZone per request.

I want to use a datetime picker (http://xdsoft.net/jqplugins/datetimepicker/) in my application to replace the default Simple_form datetime input (5 combo-boxes...).

For this kind of datetime picker (I search for others, it's the same), in my view, I have to use a "string" field, like this :

<%= f.input :done_at, as: :string, input_html: { :data => { :behaviour => "datetimepicker" } } %>  

When I post the form, Rails take care of the timezone and store in the database the time in UTC.
For example, I put "2014-03-14 19:45:07" (local time is Paris, so UTC +0100) in the field, and I have "2014-03-14 18:45:07" in the database, in UTC. It's correct.

But when I want to edit the information, Rails fill in the field with a wrong time. The offset timezone is lost and I have "2014-03-14 18:45:07" in the field (the UTC time), so 1 hour before the correct time.

How can I have the correct time taking care of the user timezone ? (not in UTC)

I tried the solution found on http://jessehouse.com/blog/2013/11/15/working-with-timezones-and-ruby-on-rails/ to override the display of dates, but it doesn't work.

def done_at
  super.in_time_zone(time_zone) if super && time_zone
end

If in my view, I put @action.done_at, the time is correct but not in the field.

Thanks,

Fred

有帮助吗?

解决方案

Set the value of the input explicitly. You can move @object.done_at.in_time_zone(time_zone) to a helper if you want

<%= f.input :done_at, as: :string, input_html: { :data => { :behaviour => "datetimepicker" }, :value => @object.done_at.in_time_zone(time_zone).strftime('%d-%m-%Y  %H:%M') } %> 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top