我正在尝试将用户选择的开始日期和结束日期与当前时间进行比较,以防止用户选择过去的时间。它可以工作,除非你必须选择一个时间,在我的例子中,提前 4 小时才能通过验证。
查看:
datetime_select(:start_date, ampm: true)
Controller :
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)'
关于ruby-on-rails - Rails datetime_select 在 UTC 中发布我当前的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19163176/