Tuesday, October 18, 2011

Age of a given date in months v2.0

I got to think about code in my previous blog post about calculating the age of a given date in months and thought about a little more elegant way to do it, here is my modified version:

//Calculate the approximate age in months for a given date
function getAgeInMonths(fromDateStr)
{
 var frDate = new Date(fromDateStr);
 var toDate = new Date();
 if (frDate > toDate) {
  throw "Given date is in future, invalid!";
 }

 var frAge = (frDate.getFullYear() - 1) * 12 
          + frDate.getMonth() + 1;
 var toAge = (toDate.getFullYear() - 1) * 12 
          + toDate.getMonth() + 1;

 return toAge - frAge;
}
// 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)
   {
      var ln = 'getAgeInMonths("'+arrDates[i]+'") = ' +    
         getAgeInMonths(arrDates[i]) + '<br/>';
      document.writeln(ln);
   }
}
I am basically calculating the age in months for each date since 0/0/0 AD and taking the difference between those ages. Here are the results from this version and they do match with the previous version:
Hope you find this useful.

Happy coding,
Sonny

No comments: