2013-10-03 25 views
2

我试图将用户选择的开始日期和结束日期与当前时间进行比较,以防止用户选择过去的时间。它的工作原理除非你必须提前4小时选择一个时间,以便通过验证。Rails datetime_select在UTC发布我的当前时间

查看:

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月3日09:00:00.000000000 -04:00

self.start_date是2013年10月3日09:00:00.000000000ž

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

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

回答

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

我结束了由起始日期转换为固定它一个字符串,并回到时间。奇怪的是我需要: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