Rails datetime_select将当前时间以UTC格式发布 [英] Rails datetime_select posting my current time in UTC
问题描述
我试图将用户选择的开始日期和结束日期与当前时间进行比较,以防止用户选择过去的时间。它工作,除非你必须选择一个时间,在我的情况下,提前4个小时,以便它通过验证。
查看:
datetime_select(:start_date,ampm:true)
控制器:
code> if self.start_date< DateTime.now || self.end_date< DateTime.now
errors.add(:date,'不能在过去')
end
self.start_date
正在返回我当前的时间,但在utc中是错误的。 DateTime.now
正在返回我当前的时间,但偏移量为-0400,这是正确的。
示例: / p>
我目前的时间是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
为什么会发生这种情况,什么是最好的方法来解决它?
我最后通过将start_date转换为字符串并回到时间来修复它。这是奇怪的,我需要:local
,因为on_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)
如果start_date_selected< current_time || end_date_selected< current_time
errors.add(:date,'不能在过去')
end
end
I'm trying to compare what the user selects for a start date and end date to the current time to prevent the user from selecting a time in the past. It works except you have to pick a time, in my case, 4 hours ahead in order for it to pass the validation.
View:
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
is returning my current time but in utc which is wrong. DateTime.now
is returning my current time but with an offset of -0400 which is correct.
Example:
My current time is 2013-10-03 09:00:00.000000000 -04:00
self.start_date is 2013-10-03 09:00:00.000000000 Z
DateTime.now is 2013-10-03 09:00:00.000000000 -04:00
Why is this happening and what would be the best way to fix it?
I ended up fixing it by converting the start_date to a string and back to time. It was weird that I needed :local
, as the documentation on to_time says it is the default, but it only works when it is present.
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
这篇关于Rails datetime_select将当前时间以UTC格式发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!