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

Kev*_*vin 2 ruby-on-rails date function relative-date

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

if time_ago < 1 hour, 3 weeks, 1 day, etc.
    execute me
end
Run Code Online (Sandbox Code Playgroud)

jef*_*unt 8

基本相对时间:

# If "time_ago" is more than 1 hour past the current time
if time_ago < 1.hour.ago
  execute_me
end
Run Code Online (Sandbox Code Playgroud)


比较:

使用a <来查看是否time_ago早于1.hour.ago,并>查看是否time_ago更新1.hour.ago


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

正如davidb所提到的那样,你可以将时间结合起来:

(1.day + 3.hours + 2500.seconds).ago
Run Code Online (Sandbox Code Playgroud)

您还可以执行小数秒,例如: 0.5.seconds.ago

没有.milliseconds.ago,所以如果你需要毫秒精度,那就把它分解成一小段时间.也就是说,1毫秒前是:

0.001.seconds.ago
Run Code Online (Sandbox Code Playgroud)


.ago()一般:

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

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

(1/2.0).hour.ago   # half hour ago
(1/4.0).year.ago   # quarter year ago
Run Code Online (Sandbox Code Playgroud)

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