'Elegant way to calculate number of years between two dates in rails?
I currently have this less-than-ideal solution:
def years_between_dates(date_from, date_to)
((date_to.to_time - date_from.to_time) / 1.year.seconds).floor
end
The calculation doesn't have to be exact (w/ leap years etc), but does need to be fairly accurate and take into account months. 3.8 years should return 3 years, hence the floor.
I am converting to_time to account for both Date, Time, and DateTime.
I can't help but think there is a more succinct way of doing the above.
Solution 1:[1]
Seems like yours is in fact the most elegant way.
Even in the definition of distance_of_time_in_words rails has:
distance_in_minutes = ((to_time - from_time) / 60.0).round
distance_in_seconds = (to_time - from_time).round
A little better version could be:
def years_between_dates(date_from, date_to)
((date_to - date_from) / 365).floor
end
Solution 2:[2]
I stumbled across this looking for something else...
Am I crazy? Can't you just do:
def years_between_dates(date_from, date_to)
date_to.year - date_from.year
end
or if you needed it to say "years" afterwards:
def years_between_dates(date_from, date_to)
return "#{date_to.year - date_from.year} years"
end
Solution 3:[3]
if you want to get the real years between two dates, you have to consider the months and days, for example if you want to get the dates between 2010-10-01 to 2021-09-09 , the real years must be 10 years. Then you can use the next function:
def years_between_dates(since_date, until_date)
years = until_date.year - since_date.year
if (until_date.month < since_date.month) ||
(until_date.month == since_date.month && until_date.day < since_date.day)
years -= 1
end
years
end
Solution 4:[4]
Simple as:
((Time.now-1.year.ago)/1.year).abs
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | bryanfeller |
| Solution 3 | Community |
| Solution 4 |
