【问题标题】:How can i prefill datetime_select with times in custom time zone?如何使用自定义时区的时间预填充 datetime_select?
【发布时间】:2013-03-04 19:07:08
【问题描述】:

我有事件可以在不同的时区

edit 时,我希望时间和日期与该事件的时区一起显示。

但是,当我点击 edit 时,datetime_select 总是显示用户时区的时间(而不是事件的时间)。

示例:

  • 活动于上午 10 点在阿姆斯特丹 (GMT+1) 开始
  • 用户时区配置为伦敦 (GMT+0)

结果:在编辑时,事件时间被错误地预设为上午 9 点

代码 sn-p:

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

  # [...]
end

请注意,@event.time_zone 包含所需的时区(上例中的“阿姆斯特丹”)。

如何在编辑时将datetime_select 预设为相应区域中的事件时间?

【问题讨论】:

  • 我能够确认这在 Rails 3.2.6 中工作正常(使用相同的编辑操作代码)。错误报告(包括解决方法)提交至github.com/rails/rails/issues/9610

标签: ruby-on-rails controller ruby-on-rails-3.2 timezone edit


【解决方案1】:

正如 pixeltrix 在错误报告的主题中指出的那样,重写相关属性的读取器/获取器会更简洁,如下所示:

# 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

这样可以省略问题中概述的编辑操作中的逻辑,并避免与依赖Time.zone的其他部分发生干扰。

【讨论】:

    猜你喜欢
    • 2018-05-15
    • 1970-01-01
    • 2016-08-30
    • 2021-04-15
    • 1970-01-01
    • 2017-06-30
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多