Rails datetime_select以UTC格式发布当前时间

我正在尝试将用户为开始日期和结束日期选择的内容与当前时间进行比较,以防止用户选择过去的时间。 它的工作原理除了你需要选择一个时间,在我的情况下,提前4个小时才能通过validation。

视图:

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

为什么会发生这种情况以及解决问题的最佳方法是什么?

你可以做这样的事情

 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)' 

我最终通过将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