I think that this does the right thing:

rick@frodo:/public/rubyscripts$ cat datemath.rb

#!/usr/math/bin/ruby

require ‘date’

class Date

# return the number of days since the beginning of the year

def years_since(date)

# The parens in the expression below aren’t strictly necessary, but

# I think it makes what’s going on a little bit clearer.

first, last = *(self >= date ? : [self, date])

(self <=> date) * ((last.year - first.year) - (first.yday >

last.yday ? 1 : 0))

end

end

def tryit(d1,d2)

puts “There are #{d1.years_since(d2)} years between #{d2} and #{d1}”

end

tryit(Date.new(2007,3,15), Date.new(2000,3,14))

tryit(Date.new(2000,3,14), Date.new(2007,3,15))

tryit(Date.new(2007,3,15), Date.new(2000,3,15))

tryit(Date.new(2007,3,15), Date.new(2000,3,16))

tryit(Date.new(2000,3,16), Date.new(2007,3,15))

tryit(Date.new(2007,2,27), Date.new(2000,2,29))

tryit(Date.new(2000,2,29), Date.new(2000,2,27))

tryit(Date.new(2007,2,28), Date.new(2000,2,29))

tryit(Date.new(2000,2,29), Date.new(2007,2,28))

tryit(Date.new(2000,2,29), Date.new(2007,3,1))

tryit(Date.new(2007,3,1), Date.new(2000,2,29))

tryit(Date.new(2007,3,2), Date.new(2000,2,29))

tryit(Date.new(2000,2,29), Date.new(2007,3,2))

rick@frodo:/public/rubyscripts$ ruby datemath.rb

There are 7 years between 2000-03-14 and 2007-03-15

There are -7 years between 2007-03-15 and 2000-03-14

There are 6 years between 2000-03-15 and 2007-03-15

There are 6 years between 2000-03-16 and 2007-03-15

There are -6 years between 2007-03-15 and 2000-03-16

There are 6 years between 2000-02-29 and 2007-02-27

There are 0 years between 2000-02-27 and 2000-02-29

There are 6 years between 2000-02-29 and 2007-02-28

There are -6 years between 2007-02-28 and 2000-02-29

There are -7 years between 2007-03-01 and 2000-02-29

There are 7 years between 2000-02-29 and 2007-03-01

There are 7 years between 2000-02-29 and 2007-03-02

There are -7 years between 2007-03-02 and 2000-02-29

–

Rick DeNatale

My blog on Ruby

http://talklikeaduck.denhaven2.com/