Skip to content

Instantly share code, notes, and snippets.

@ljsc
Forked from anonymous/snippet.rb
Created November 20, 2008 21:18
Show Gist options
  • Save ljsc/27205 to your computer and use it in GitHub Desktop.
Save ljsc/27205 to your computer and use it in GitHub Desktop.
require 'date'
module DateDiff
module_function
def difference_in_months(d1, d2)
DateDifference.new(d1,d2).months
end
class DateDifference
def initialize(d1, d2)
@d1, @d2 = [d1, d2].map {|a| coerce_arg(a)}
@positive = @d1 > @d2
@d1, @d2 = @d2, @d1 unless positive?
end
def months
month_difference = if @d1.month >= @d2.month
month_difference = @d1.month - @d2.month
else
month_difference = 12 - @d2.month + @d1.month
end
months = 12 * years + month_difference
positive? ? months : months * -1
end
def years
if @d1.month >= @d2.month
@d1.year - @d2.year
else
@d1.year - @d2.year - 1
end
end
def positive?
!!@positive
end
protected
def coerce_arg(arg)
case arg
when String
Date.parse(arg)
when Date
arg
else
raise ArgumentError, 'Expecting some sort of date data'
end
end
end
end
require 'test/unit'
module Test
class DateTests < Test::Unit::TestCase
def setup
@els = Date.parse('Jul 2005')
@msd = Date.parse('Apr 2002')
end
include DateDiff
def test_one_month
assert_equal 1, difference_in_months('Jul 2005', 'Jun 2005')
end
def test_neg_on_month
assert_equal -1, difference_in_months('Jul 2005', 'Aug 2005')
end
def test_year_fakeout
assert_equal 2, difference_in_months('Jan 2009', '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