by Matt Coughlin

getAgeInYears:

Goal:

Example:

Birthday:



Choose a Day:



Implementation notes:

HTML:

<select size="1" name="dobMonth" id="dobMonth">...</select>
<select size="1" name="dobDay" id="dobDay">...</select>
<select size="1" name="dobYear" id="dobYear">...</select>
<input type="button" value="Get Current Age" id="currentAge"/>

<select size="1" name="pastMonth" id="pastMonth">...</select>
<select size="1" name="pastDay" id="pastDay">...</select>
<select size="1" name="pastYear" id="pastYear">...</select>
<input type="button" value="Get Age on This Day" id="pastAge"/>
        

JavaScript:

// Get current age
$('#currentAge').click(function(){
    var dobYear = $('#dobYear').val();
    var dobMonth = $('#dobMonth').get(0).selectedIndex;
    var dobDay = $('#dobDay').get(0).selectedIndex + 1;
    

    var birthday = new Date(dobYear, dobMonth, dobDay);   // Birthday
    var now = new Date();                                 // Current date
    var age = now.getAgeInYears(birthday);
    alert(age);
});

// Get past age
$('#pastAge').click(function(){
    var dobYear = $('#dobYear').val();
    var dobMonth = $('#dobMonth').get(0).selectedIndex;
    var dobDay = $('#dobDay').get(0).selectedIndex + 1;

    var pastYear = $('#pastYear').val();
    var pastMonth = $('#pastMonth').get(0).selectedIndex;
    var pastDay = $('#pastDay').get(0).selectedIndex + 1;
    
    var birthday = new Date(dobYear, dobMonth, dobDay);   // Birthday
    var past = new Date(pastYear, pastMonth, pastDay);    // Past date
    var age = past.getAgeInYears(birthday);
    alert(age);
});
        

getAgeInYears.js