1

我正在使用 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
4

2 回答 2

1

Time.zone有一个parse方法,它也返回一个ActiveSupport::TimeWithZone

>> Time.zone.parse "October 4 1984"
=> Thu, 04 Oct 1984 00:00:00 EDT -04:00

为了让它与慢性病一起玩,也许这篇文章可以提供帮助?例如,如果您要将一个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
于 2010-11-09T19:30:23.490 回答
1

看这里:TimeWithZone有一个构造函数,它采用 utc 格式的普通 Time 对象和一个时区。所以,如果有时间,你可以试试这个:

ActiveSupport::TimeWithZone.new(Chronic.parse(self.natural_date).utc, Time.zone)
于 2010-11-09T19:48:26.180 回答