Rails 'config.time_zone' doesn't apply to datetime data loaded into a text_field. Fix?

后端 未结 2 1980
天命终不由人
天命终不由人 2020-12-09 12:39

When I use a datetime_select in my form, Rails will correctly adjust the timezone of the datetime data (as per my config.time_zone setting), and will render the

相关标签:
2条回答
  • 2020-12-09 13:26

    As I said in the question, the main problem I had was getting ActiveRecord to apply the existing 'config.time_zone' setting to text_fields.

    It turns out that there's a very simple and future-proof way to make that happen: just explicitly add a :value and pull the exact same data--no extra/new methods to call! In my case, that meant:

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

    This was an intermediary step to another potential solution I was going to try, and I was surprised to find that it worked all on its own (again, working with the 'config.time_zone' I'd already set in 'config/application.rb').

    I've tested it, and it applies the proper DST offset when applicable as well (just as one would expect, since 'config.time_zone' is set).

    0 讨论(0)
  • 2020-12-09 13:27

    How about converting it with TimeZone#utc_to_local?

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

    0 讨论(0)
提交回复
热议问题