Monday, October 17, 2011

Age of a given date in months

Have you ever tried to calculate the age of a given date in months using Javascript? Well, a co-worker looking for a way to do that. It does not have to use the date (day of the month), but just a rough calculation of age in months.

Here is what I have come up with:
//Calculate the approximate age in months for a given date
function getAgeInMonths(fromDateStr)
{
   var frDate = new Date(fromDateStr);
   var toDate = new Date();

   if (toDate.getFullYear() == frDate.getFullYear())
      return toDate.getMonth() - frDate.getMonth();
   else 
      return (12 - frDate.getMonth() - 1) + 
      ((toDate.getFullYear()-frDate.getFullYear()-1) * 12) 
      + (toDate.getMonth() + 1);
}

// test function to check some random dates
function test_getAgeInMonths()
{
   var arrDates = ['2011/05/01', '2010/09/05', '2002/02/25', '1980/03/23'];
   for (var i=0; i < arrDates.length; ++i)
   {
      document.writeln('getAgeInMonths("' + arrDates[i] + 
         '") = ' +       
         getAgeInMonths(arrDates[i]) + '
'); } }

Optionally you might want to use the isDate function to check the date string being passed-in is in valid date format or not.
The code is self explanatory and when you run the test function, you get the following results:

Hope you find this useful.

Happy coding,

Sonny

No comments: