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