Rails Form display datetime at local timezone

倾然丶 夕夏残阳落幕 提交于 2019-12-11 11:03:03

问题


I'm new to rails (just finished the Rails Tutorial) and I'm building my first solo app. The user can create 'events' at specific times. Currently the user form is in UTC. How do I set it to their local time?

I don't just want to change it after they submit, because it would be confusing for the user. When you open a new form the default time is the current time (currently UTC). I want that to be the time of their local timezone.

    <%= f.label :Date_Time %><br />
    <%= f.datetime_select :date %>

thanks,


回答1:


Loads of ways to do this!

I'd recommend you look at the question Stepan recommended first


Server Side

If you're wanting to keep your times consistent, you may wish to use the Rails in-built timezone option:

#config/application.rb
config.time_zone = 'Eastern Time (US & Canada)'

You can see more about ActiveSupport::Timezone here


Client-Side

Client-side, you'd have to think about what you want to achieve. If you have set timezones, you may benefit from creating a TimeZone repository (either ENV variables or datatable), and allow user to select from them, like this:

#app/views/form.html.erb
<%= form_tag %>
    <%= select_tag :date, options_from_collection_for_select(@timezones, "id", "name") %>
<% end %>

Alternatively, you could pass the timezone through javascript: Getting the client's timezone in JavaScript


UX

The bottom line is you need to think about what you're trying to achieve. If your users need localized times, you should use a country-select system, where they will give you their country, and you can dedicate a timezone

Speaking from experience, it's much better to store all times equally (using UTC), and then process them using user's specifications



来源:https://stackoverflow.com/questions/21058450/rails-form-display-datetime-at-local-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!