Compare dates and get the difference

What’s the best way to do math with RoR?

I’m trying to compare two different records based on their timestamp,
and I want to wind up with the difference between the two. (i.e. Number
of days between the two timestamps)

I’ve tried using math, like subtraction, but it doesn’t seem to work
that way.


Standard comparison operators should do the trick. Here’s an example
of what I am doing:

  now =
  days_ago = now.ago(days.to_i * (60*60*24))
  if p.sold_at > days_ago then
    yada yada

On Jun 18, 2007, at 2:00 PM, jf wrote:


A timestamp is probably a Time and subtraction gives the number of
seconds between the two. If you convert to Date, subtraction gives
days. - 18.seconds.ago
=> 17.999993 - 3.days.ago
=> 259199.999989
=> #<Date: 4908539/2,0,2299161>
=> “2007-06-18”

=> “2007-06-15” - 3.days.ago.to_date
=> Rational(3, 1)

( - 3.days.ago.to_date).to_i
=> 3

( - 3.days.ago.to_date)
=> Rational(3, 1)

( - 3.days.ago.to_date).to_i
=> 3


Rob B.
[email protected]

( - 3.days.ago.to_date).to_i
=> 3

I believe the above is what I need.


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs