How to present Rails form datetime select in diffe

2019-08-07 09:56发布

I would like to present a datetime select to the user in their preferred time zone but store the datetime as UTC. Currently, the default behavior is to display and store the datetime field using UTC. How can I change the behavior of this field without affecting the entire application (i.e. not changing the application default time zone)?

Update: This is not a per-user timezone. I don't need to adjust how times are displayed. Only these specific fields deal with a different time zone, so I would like the user to be able to specify the time in this time zone.

2条回答
劫难
2楼-- · 2019-08-07 10:03

Here's how you can allow the user to set a date using a specific time zone:

To convert the multi-parameter attributes that are submitted in the form to a specific time zone, add a method in your controller to manually convert the params into a datetime object. I chose to add this to the controller because I did not want to affect the model behavior. You should still be able to set a date on the model and assume your date was set correctly.

def create
  convert_datetimes_to_pdt("start_date")
  convert_datetimes_to_pdt("end_date")
  @model = MyModel.new(params[:my_model])
  # ...
end

def update
  convert_datetimes_to_pdt("start_date")
  convert_datetimes_to_pdt("end_date")
  # ...
end

def convert_datetimes_to_pdt(field)
  datetime = (1..5).collect {|num| params['my_model'].delete "#{field}(#{num}i)" }
  if datetime[0] and datetime[1] and datetime[2] # only if a date has been set
    params['my_model'][field] = Time.find_zone!("Pacific Time (US & Canada)").local(*datetime.map(&:to_i))
  end
end

Now the datetime will be adjusted to the correct time zone. However, when the user goes to edit the time, the form fields will still display the time in UTC. To fix this, we can wrap the fields in a call to Time.use_zone:

Time.use_zone("Pacific Time (US & Canada)") do
  f.datetime_select :start_date
end
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-08-07 10:08

There are a couple of options:

  • Utilize the user's local timezone when displaying data to them. This is really easy with something like the browser-timezone-rails gem. See https://github.com/kbaum/browser-timezone-rails. It is essentially overriding the application timezone for each request based on the timezone detected from the browser. NOTE: it only uses the OS timezone, so it's not as accurate as an IP/geo based solution.
  • Setup your application timezone so that it is consistent with the majority of your user base. For example: config.time_zone = 'Mountain Time (US & Canada)'. This is a very standard thing to do in rails. Rails will always store the data in the DB as UTC, but will present / load it using the application timezone.
  • Create a timezone for your user model. Allow users to set this value in their account settings. And, then use a similar approach to that of the above gem does in the application_controller.
查看更多
登录 后发表回答