Rails Form display datetime at local timezone

2019-08-14 01:55发布

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条回答
聊天终结者
2楼-- · 2019-08-14 02:31

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

查看更多
登录 后发表回答