2

I need to know how to do relative time in rails but not as a sentence, more like something i could do this with (when i input format like this 2008-08-05 23:48:04 -0400)

if time_ago < 1 hour, 3 weeks, 1 day, etc.
    execute me
end
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Kevin
  • 1,574
  • 4
  • 19
  • 45

2 Answers2

9

Basic relative time:

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


Comparison:

Use a < to see if time_ago is older than 1.hour.ago, and > to see if time_ago is more recent than 1.hour.ago


Combining times, and using fractional times:

You can combine times, as davidb mentioned, and do:

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

You can also do fractional seconds, like: 0.5.seconds.ago

There is no .milliseconds.ago, so if you need millisecond precision, just break it out into a fractional second. That is, 1 millisecond ago is:

0.001.seconds.ago


.ago() in general:

Putting .ago at the end of just about any number will treat the number as a #of seconds.

You can even use fractions in paranthesis:

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

NOTE: to use fractions, either the numerator or denominator needs to be a floating point number, otherwise Ruby will automatically cast the answer to an integer, and throw off your math.

jefflunt
  • 33,527
  • 7
  • 88
  • 126
3

You mean sth. like this?

if time_ago < Time.now-(1.days+1.hour+1.minute)
    execute me
end
davidb
  • 8,884
  • 4
  • 36
  • 72