我正在使用Chronic来解析时间,它正在返回此错误:
ArgumentError in EventsController#create
comparison of Date with ActiveSupport::TimeWithZone failed
这是因为自从Rails 2.1以来,数据库和Ruby都在不同的时区。
如何将我的声明转换为工作?
def set_dates
unless self.natural_date.blank? || Chronic.parse(self.natural_date).blank?
# check if we are dealing with a date or a date + time
if time_provided?(self.natural_date)
self.date = nil
self.time = Chronic.parse(self.natural_date)
else
self.date = Chronic.parse(self.natural_date).to_date
self.time = nil
end
end
答案 0 :(得分:1)
Time.zone
有一个parse
方法,该方法也返回ActiveSupport::TimeWithZone
:
>> Time.zone.parse "October 4 1984"
=> Thu, 04 Oct 1984 00:00:00 EDT -04:00
为了让它与慢性病一起玩,也许this article会有帮助吗?例如,如果您要将parse_with_chronic
方法修补到ActiveSupport::TimeZone
,那么您可以重写您的方法:
def set_dates
unless self.natural_date.blank? || Time.zone.parse_with_chronic(self.natural_date).blank?
# check if we are dealing with a date or a date + time
if time_provided?(self.natural_date)
self.date = nil
self.time = Time.zone.parse_with_chronic(self.natural_date)
else
self.date = Time.zone.parse_with_chronic(self.natural_date).to_date
self.time = nil
end
end
end
答案 1 :(得分:1)
请看这里:TimeWithZone有一个构造函数,它在utc和时区中采用正常的Time对象。所以,给定时间你可以试试这个:
ActiveSupport::TimeWithZone.new(Chronic.parse(self.natural_date).utc, Time.zone)