在Rails中使用和比较相对时间



我需要知道如何在rails中做相对时间,但不是作为一个句子,更像是我可以这样做的东西(当我输入这样的格式2008-08-05 23:48:04 -0400)

if time_ago < 1 hour, 3 weeks, 1 day, etc.
    execute me
end

基本相对时间:

# If "time_ago" is more than 1 hour past the current time
if time_ago < 1.hour.ago
  execute_me
end


<标题>比较:

使用<查看time_ago是否比1.hour.ago更老,使用>查看time_ago是否比1.hour.ago更新


组合时间,并使用小数次:

你可以组合时间,就像davidb提到的那样:

(1.day + 3.hours + 2500.seconds).ago

你也可以设置小数秒,比如:0.5.seconds.ago

没有.milliseconds.ago,所以如果您需要毫秒级的精度,只需将其分解为小数秒。也就是说,1毫秒前是:

0.001.seconds.ago


.ago()一般:

.ago放在几乎任何数字的末尾都会将该数字视为秒数。

你甚至可以在括号中使用分数:

(1/2.0).hour.ago   # half hour ago
(1/4.0).year.ago   # quarter year ago

注意:要使用分数,分子或分母都需要是浮点数,否则Ruby会自动将答案转换为整数,并抛弃您的数学。

你是说这样的事吗?

if time_ago < Time.now-(1.days+1.hour+1.minute)
    execute me
end

相关内容

最新更新