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.
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
Reference
A little better version could be:
def years_between_dates(date_from, date_to)
((date_to - date_from) / 365).floor
end
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With