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.

Thanks

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

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

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

Thanks

A timestamp is probably a Time and subtraction gives the number of
seconds between the two. If you convert to Date, subtraction gives
days.

Time.now - 18.seconds.ago
=> 17.999993
Time.now - 3.days.ago
=> 259199.999989

Date.today
=> #<Date: 4908539/2,0,2299161>
Date.today.to_s
=> “2007-06-18”
3.days.ago.to_date.to_s
=> “2007-06-15”

Time.now.to_date - 3.days.ago.to_date
=> Rational(3, 1)
(Time.now.to_date - 3.days.ago.to_date).to_i
=> 3
(Date.today - 3.days.ago.to_date)
=> Rational(3, 1)
(Date.today - 3.days.ago.to_date).to_i
=> 3

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

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

I believe the above is what I need.

Thanks!