0 votes
924 views
in jQuery by
How can calculate age from date of birth in jquery?

1 Answer

0 votes
by (3.7k points)
edited by

See the following code:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">    
$(document).ready(function(){
    $("#btnCal").click(function(){
        var dob = $("#dob").val();
        var arrDob = dob.split("-");
        showAge(arrDob[0], arrDob[1], arrDob[2]);
    });
});

function showAge(dobYear, dobMonth, dobDay) {
    var bthDate, curDate, days;
    var ageYears, ageMonths, ageDays;
    bthDate = new Date(dobYear, dobMonth-1, dobDay);
    curDate = new Date();
    if (bthDate>curDate) return;
    days = Math.floor((curDate-bthDate)/(1000*60*60*24));
    ageYears = Math.floor(days/365);
    ageMonths = Math.floor((days%365)/31);
    ageDays = days - (ageYears*365) - (ageMonths*31);
    var calDOB = "";
    if (ageYears>0) {
        calDOB = ageYears+" year";
        if (ageYears>1) calDOB +="s";
        if ((ageMonths>0)||(ageDays>0)) calDOB += ", ";
    }
    if (ageMonths>0) {
        calDOB += ageMonths+" month";
        if (ageMonths>1) calDOB += "s";
        if (ageDays>0) calDOB += ", ";
    }
    if (ageDays>0) {
        calDOB += ageDays+" day";
        if (ageDays>1) calDOB += "s";
    }
    $("#calculatedDob").val(calDOB);
}
</script>
</head>
<body>
    <b>Date of Birth:</b> <input type="text" name="dob" id="dob" value="2005-02-17" /><br><br>
    <b>Calculated Age:</b> <input type="text" name="calculatedDob" id="calculatedDob" /><br><br><br>
    <input type="button" id="btnCal" name="btnCal" value="Calculate Age" />
</body>
</html>

Result:

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...