【问题标题】:Rails datetime_select posting my current time in UTCRails datetime_select 在 UTC 中发布我的当前时间
【发布时间】:2013-10-03 15:29:22
【问题描述】:

我正在尝试将用户选择的开始日期和结束日期与当前时间进行比较,以防止用户选择过去的时间。它可以工作,除非你必须选择一个时间,在我的情况下,提前 4 小时才能通过验证。

查看:

datetime_select(:start_date, ampm: true)

控制器:

if self.start_date < DateTime.now || self.end_date < DateTime.now
  errors.add(:date, 'can not be in the past.')
end

self.start_date 正在返回我当前的时间,但在 UTC 中这是错误的。 DateTime.now 正在返回我的当前时间,但偏移量为 -0400,这是正确的。

例子:

我现在的时间是 2013-10-03 09:00:00.000000000 -04:00

self.start_date 是 2013-10-03 09:00:00.000000000 Z

DateTime.now 是 2013-10-03 09:00:00.000000000 -04:00

为什么会发生这种情况,最好的解决方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby datetime timezone


    【解决方案1】:

    你可以这样做

    around_filter :set_time_zone
    
    private
    
    def set_time_zone
      old_time_zone = Time.zone
      Time.zone = current_user.time_zone if logged_in?
      yield
    ensure
      Time.zone = old_time_zone
    end
    

    你也可以这样做

    将以下内容添加到 application.rb 作品

     config.time_zone = 'Eastern Time (US & Canada)'
     config.active_record.default_timezone = 'Eastern Time (US & Canada)'
    

    【讨论】:

      【解决方案2】:

      我最终通过将 start_date 转换为字符串并返回时间来修复它。我需要:local 很奇怪,因为 to_time 上的文档说它是默认设置,但它只在它存在时才有效。

      def not_past_date
      
        current_time = DateTime.now
        start_date_selected = self.start_date.to_s.to_time(:local)
        end_date_selected = self.start_date.to_s.to_time(:local)
      
        if start_date_selected < current_time || end_date_selected < current_time
          errors.add(:date, 'can not be in the past.')
        end
      end
      

      【讨论】:

        猜你喜欢
        • 2020-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多