Skip to content

Instantly share code, notes, and snippets.

@mkaschenko
Last active March 1, 2025 06:24
Show Gist options
  • Select an option

  • Save mkaschenko/13a1d4a6942c4fd898600d681d91f03a to your computer and use it in GitHub Desktop.

Select an option

Save mkaschenko/13a1d4a6942c4fd898600d681d91f03a to your computer and use it in GitHub Desktop.
The difference in years between dates
# Year 2017
module Date
# NOTE: There are two scenarios to consider based on the order of input dates:
# 1. Ascending order: Only negative differences in days and/or months affect the year count.
# 2. Descending order: Only positive differences in days and/or months affect the year count.
def self.difference_in_years(left_date, right_date)
diff_in_years = right_date.year - left_date.year
diff_in_months = (right_date.month - left_date.month) / 100.0
diff_in_days = (right_date.day - left_date.day) / 10_000.0
(diff_in_years + diff_in_months + diff_in_days).truncate
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment