0

我目前正在尝试创建一种减去两个日期的方法。这是它的样子:(成熟是未来的时间)

  def time_remaining
    # If validated, return time between now and number of days from validation.
    if self.is_validated?
      return (self.maturity > Time.now) ? (self.maturity - Time.now) : 0
    # If not validated, return number of days converted in time
    else
      return self.nb_days.nil? ? 0 : self.nb_days.days
    end
  end

在我看来,我这样做:

distance_of_time_in_words(project.time_remaining)

这可行,但这不是我真正想做的,如果减法的结果小于一天,我想要检索几个小时,如果减法的结果检索几分钟小于一个小时,如果结果大于一天,则检索天数。

成熟度是在这种格式下:Wed, 27 Nov 2013 12:42:09 UTC +00:00。你能告诉我至少一个关于我该怎么做的提示吗?

编辑 :

我试过这样的东西,但它真的很乱:

def time_remaining
    # If validated, return time between now and number of days from validation.
    if self.is_validated?
      if (self.maturity > Time.now)
        if ((self.maturity - Time.now)/1.day < 1)
          return (self.maturity - Time.now)/1.day.
        elsif ((self.maturity - Time.now) < 1.hour)
          return (self.maturity - Time.now)/1.min
        else
          return (self.maturity - Time.now)
        end
      else
        0
      end
    # If not validated, return number of days converted in time
    else
      return self.nb_days.nil? ? 0 : self.nb_days.days
    end
  end

关键是要去掉distance_of_time_in_words这里。

解决方案:感谢@Rafał Cieślak 和 gem time_diff。这是我所做的:

  def remaining_time (project)
    if project.is_validated?
      if ((project.maturity - Time.now)/1.day >= 1)
        result = Time.diff(project.maturity, Time.now, '%d')
        return result[:diff]
      elsif ((project.maturity - Time.now)/1.hour > 1 && (project.maturity - Time.now)/1.hour < 24)
        result = Time.diff(project.maturity, Time.now, '%H')
        return result[:diff]
      elsif ((project.maturity - Time.now)/1.hour < 1)
        result = Time.diff(project.maturity, Time.now, '%N')
        return result[:diff]
      end
    else
      return project.nb_days.nil? ? 0 : project.nb_days.days
    end
  end
4

1 回答 1

2

这是我很快破解的东西。您需要安装time_diff gem 并使用以下方法作为助手(不在您的模型中)。

def time_remaining(time_start, time_end)
  diff_hash = Time.diff(time_start, time_end)
  diff_hash.delete :diff
  output = []

  diff_hash.each do |key, value|
    output.push(pluralize(value, key.to_s)) if value > 0
  end

  output.join(', ')
end

例子:

>> time_remaining 2.days.ago.change(min: 58, hour: 15), Time.now
=> "1 day, 20 hours, 19 minutes, 24 seconds"
>> time_remaining 34.minutes.ago.change(sec: 15), Time.now
=> "33 minutes, 53 seconds"
于 2013-09-05T12:19:33.760 回答