如何在不同时区中显示Rails表单的datetime选择? [英] How to present Rails form datetime select in different time zone?

查看:43
本文介绍了如何在不同时区中显示Rails表单的datetime选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向用户提供其首选时区中的日期时间选择,但将日期时间存储为UTC.当前,默认行为是使用UTC显示和存储datetime字段.如何在不影响整个应用程序的情况下更改此字段的行为(即不更改应用程序的默认时区)?

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.

推荐答案

以下是允许用户使用特定时区设置日期的方法:

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

要将表单中提交的多参数属性转换为特定时区,请在控制器中添加一个方法,以将参数手动转换为datetime对象.我选择将其添加到控制器,因为我不想影响模型行为.您仍然应该能够在模型上设置日期,并假设您的日期设置正确.

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

现在,日期时间将被调整为正确的时区.但是,当用户去编辑时间时,表单字段仍将以UTC显示时间.为了解决这个问题,我们可以将这些字段包装在对 Time.use_zone :

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

这篇关于如何在不同时区中显示Rails表单的datetime选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆