28

哈哈..

我正在使用 Chronic 来解析用户在日历中添加的时间。在代码工作并实现正确时间的地方,最终结果是,如果用户添加时间,则它没有日期,并且因为它没有日期,所以它不会显示在结果中。有任何想法吗?

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

  unless self.natural_end_date.blank? || Chronic.parse(self.natural_end_date).blank?
    # check if we are dealing with a date or a date + time
    if time_provided?(self.natural_end_date)
      self.end_date = nil
      self.end_time = Chronic.parse(self.natural_end_date)
    else
      self.end_date = Chronic.parse(self.natural_end_date).to_date
      self.end_time = nil
    end
  end
end

编辑:

这是time_provided?方法:

def time_provided?(natural_date_string)
  date_span = Chronic.parse(natural_date_string, :guess => false)
  (date_span.last - date_span.first).to_i == 1
end
4

1 回答 1

3

首先,我不太确定你在问什么,因为看起来代码是故意按照你的描述做的......当有时间提供时,日期字段被分配nil。我不认为慢性病是罪魁祸首,因为这就是你的代码的工作方式。

不知道您的设计(为什么有单独的日期和时间字段)、字段的类型等,我建议从这样的小杂烩开始:

if time_provided?(self.natural_date)
  self.time = Chronic.parse(self.natural_date)
  self.date = self.time.to_date

或者:

self.end_date = Chronic.parse(self.natural_date).to_date
if time_provided?(self.natural_date)
  self.time = Chronic.parse(self.natural_date)
end

Or maybe the problem is outside the code you provided: in the part that is responsible for the "because it has no date, it will not show in results" behavior? Maybe you should make the conditions more flexible?

于 2010-05-13T07:44:06.447 回答