How can i prefill datetime_select with times in custom time zone?

爱⌒轻易说出口 提交于 2019-12-01 06:12:21

问题


I have events that can be in different time zones.

Upon edit I want the time & date to show with the time zone of that very event.

However, when I hit edit, datetime_select always shows the time of the users time zone (as opposed to the one of the event).

Example:

  • Event starting at 10 a.m. in Amsterdam (GMT+1)
  • Users time zone configured as London (GMT+0)

Result: Upon edit the event time is falsely preset to 9 a.m.

Code snippet:

def edit
  Time.zone = @event.time_zone
  @event.beginn = @event.beginn.in_time_zone
  @event.endd = @event.endd.in_time_zone

  # [...]
end

Note that @event.time_zone contains the desired time zone ("Amsterdam" in the above example).

How can I have datetime_select preset to the events time in it's respective zone upon edit?


回答1:


As pixeltrix pointed out in the thread of the bug report, it's cleaner to override the readers/getters of the attributes in question like so:

# in event model

def beginn
  super.in_time_zone(time_zone) if super
end

def endd
    super.in_time_zone(time_zone) if super
end

This way the logic in the edit action as outlined in the question can be omitted and interferences with other parts that rely on Time.zone are avoided.



来源:https://stackoverflow.com/questions/15209130/how-can-i-prefill-datetime-select-with-times-in-custom-time-zone

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