Skip to content Skip to sidebar Skip to footer

Calculating Age In Months And Days

function getAge(dateString) { var today = new Date(); var birthDate = new Date(dateString); var age = today.getFullYear() - birthDate.getFullYear(); var m = today.g

Solution 1:

It often happens that you want to know the age a person would be on a specific date, or the years, months and days between two dates.

If you do want the age as-of today, pass a single date or datestring argument.

functiongetAge(fromdate, todate){
    if(todate) todate= newDate(todate);
    else todate= newDate();

    var age= [], fromdate= newDate(fromdate),
    y= [todate.getFullYear(), fromdate.getFullYear()],
    ydiff= y[0]-y[1],
    m= [todate.getMonth(), fromdate.getMonth()],
    mdiff= m[0]-m[1],
    d= [todate.getDate(), fromdate.getDate()],
    ddiff= d[0]-d[1];

    if(mdiff < 0 || (mdiff=== 0 && ddiff<0))--ydiff;
    if(mdiff<0) mdiff+= 12;
    if(ddiff<0){
        fromdate.setMonth(m[1]+1, 0);
        ddiff= fromdate.getDate()-d[1]+d[0];
        --mdiff;
    }
    if(ydiff> 0) age.push(ydiff+ ' year'+(ydiff> 1? 's ':' '));
    if(mdiff> 0) age.push(mdiff+ ' month'+(mdiff> 1? 's':''));
    if(ddiff> 0) age.push(ddiff+ ' day'+(ddiff> 1? 's':''));
    if(age.length>1) age.splice(age.length-1,0,' and ');    
    return age.join('');
}


getAge("1/25/1974")>> 37 years 8 months and 26 days

getAge("9/15/1984")>> 27 years 1 month and 5 days

getAge("12/20/1984","10,20,2011")>>26 years  and 9 months

getAge(newDate(),"12/25/2011")+' till Christmas'>>
2 months and 5 days till ChristmasgetAge("6/25/2011")>> 3 months and 25 days

Solution 2:

With this you can have a descriptive age text : Days, Months and Years:

functiongetAge(dateString) {

  var birthdate = newDate(dateString).getTime();
  var now = newDate().getTime();
  // now find the difference between now and the birthdatevar n = (now - birthdate)/1000;

  if (n < 604800) { // less than a weekvar day_n = Math.floor(n/86400);
    return day_n + ' day' + (day_n > 1 ? 's' : '');
  } elseif (n < 2629743) {  // less than a monthvar week_n = Math.floor(n/604800);
    return week_n + ' week' + (week_n > 1 ? 's' : '');
  } elseif (n < 63113852) { // less than 24 monthsvar month_n = Math.floor(n/2629743);
    return month_n + ' month' + (month_n > 1 ? 's' : '');
  } else { 
    var year_n = Math.floor(n/31556926);
    return year_n + ' year' + (year_n > 1 ? 's' : '');
  }
}


var age = getAge("01/20/2011");
alert(age);

Post a Comment for "Calculating Age In Months And Days"