日期,减法,条件和渲染

时间:2013-09-05 11:20:33

标签: ruby-on-rails date

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

  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和宝石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

1 个答案:

答案 0 :(得分: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"