Last active
March 1, 2025 06:24
-
-
Save mkaschenko/13a1d4a6942c4fd898600d681d91f03a to your computer and use it in GitHub Desktop.
The difference in years between dates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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