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

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