Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 679
Damien Roche Avatar asked Jan 15 '15 15:01

Damien Roche


2 Answers

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
like image 198
Vedant Agarwala Avatar answered Oct 13 '22 00:10

Vedant Agarwala


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
like image 23
bryanfeller Avatar answered Oct 13 '22 01:10

bryanfeller