Topic: Number of years and months between a date range

Here it is:

I have:

  joining_date = params[:joining_date]  #=>Wed, 24 Sep 2008
  current_date = Date.today  #=>Mon, 17 May 2010

What I am looking for is, the difference between the two dates so that I get the number of years and months in between the two date range, so that here in this case, i could find the total experience of an employee in an organization since his joining_date

Thanks

Re: Number of years and months between a date range

You can get the difference in days between two Date objects by subtracting them. From there it is fairly simple to work out years and months provided you don't want to get picky about how long a month is, or accounting for leap years, as this is open to interpretation when it comes to differences beween dates.

require 'date'
start_date = Date.civil(2005, 6, 16)
difference = (Date.today() - start_date).to_int
years = difference / 365
p years
So if you are trying to gauge years of experience, this would be OK. If you are using it as a legal basis for calculating severance pay entitlement, things could get a lot more complicated in a few edge and corner cases...

Re: Number of years and months between a date range

@specious

Thanks, That was helpful.
By subtracting two date object, we get the total number of days in between the two dates, using which we can calculate number of years and months.