Skip to content

Instantly share code, notes, and snippets.

Created November 20, 2008 20:40
Show Gist options
  • Save anonymous/27183 to your computer and use it in GitHub Desktop.
Save anonymous/27183 to your computer and use it in GitHub Desktop.
require 'date'
def difference_in_months(d1, d2)
positive = d1 > d2
d1, d2 = d2, d1 unless positive
month_difference = if d1.month >= d2.month
year_difference = d1.year - d2.year
month_difference = d1.month - d2.month
else
year_difference = d1.year - d2.year - 1
month_difference = 12 - d2.month + d1.month
end
months = 12 * year_difference + month_difference
positive ? months : months * -1
end
require 'test/unit'
module Test
class DateTests < Test::Unit::TestCase
def setup
@els = Date.parse('Jul 2005')
@msd = Date.parse('Apr 2002')
end
def d(str)
Date.parse(str)
end
def test_one_month
assert_equal 1, difference_in_months(d('Jul 2005'), d('Jun 2005'))
end
def test_neg_on_month
assert_equal -1, difference_in_months(d('Jul 2005'), d('Aug 2005'))
end
def test_year_fakeout
assert_equal 2, difference_in_months(d('Jan 2009'), d('Nov 2008'))
end
def test_example
assert_equal 39, difference_in_months(@els, @msd)
assert_equal 308, (difference_in_months(@els, @msd)*8-4)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment