Skip to content

Instantly share code, notes, and snippets.

@hokaccha
Created March 6, 2013 06:25
Show Gist options
  • Save hokaccha/5097170 to your computer and use it in GitHub Desktop.
Save hokaccha/5097170 to your computer and use it in GitHub Desktop.
require 'test/unit'
require 'date'
def year_diff(a, b)
month_diff = (a.year * 12 + a.month) - (b.year * 12 + b.month)
month_diff -= 1 if a.month == b.month && a.day < b.day
month_diff / 12
end
class TestYearDiff < Test::Unit::TestCase
def test_year_diff
assert_equal 1,
year_diff(Date.parse('2013-01-01'), Date.parse('2012-01-01'))
assert_equal 1,
year_diff(Date.parse('2013-01-01'), Date.parse('2011-12-31'))
assert_equal 0,
year_diff(Date.parse('2013-01-01'), Date.parse('2012-01-02'))
assert_equal 1,
year_diff(Date.parse('2012-01-01'), Date.parse('2011-01-01'))
assert_equal 1,
year_diff(Date.parse('2012-01-01'), Date.parse('2010-12-31'))
assert_equal 0,
year_diff(Date.parse('2012-01-01'), Date.parse('2011-01-02'))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment