Reputation: 27114
I am using Chronic to parse time and it is returning this error:
ArgumentError in EventsController#create
comparison of Date with ActiveSupport::TimeWithZone failed
This is because since Rails 2.1 the database and Ruby are on different timezones.
How can I convert my statement to work ?
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
Upvotes: 1
Views: 677
Reputation: 2816
Look here: TimeWithZone has a constructor, which takes a normal Time object in utc and a timezone. So, given time is you can try this:
ActiveSupport::TimeWithZone.new(Chronic.parse(self.natural_date).utc, Time.zone)
Upvotes: 1
Reputation: 94133
Time.zone
has a parse
method, which also returns a ActiveSupport::TimeWithZone
:
>> Time.zone.parse "October 4 1984"
=> Thu, 04 Oct 1984 00:00:00 EDT -04:00
To get it playing with Chronic, maybe this article can help? If you were to, for instance, patch a parse_with_chronic
method into ActiveSupport::TimeZone
, then you could rewrite your method:
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
Upvotes: 1