2

我正在尝试将用户选择的开始日期和结束日期与当前时间进行比较,以防止用户选择过去的时间。它可以工作,除非你必须选择一个时间,在我的情况下,提前 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

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

4

2 回答 2

0

我最终通过将 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
于 2013-10-08T20:52:33.763 回答
0

你可以做这样的事情

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)'
于 2013-10-03T15:39:55.533 回答