ruby-on-railsfunctiondaterelative-date

Using and comparing relative time in Rails


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

Solution

  • 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.