Thursday, April 21, 2011

Calculate DOB Age, Years, Months, Days Using Java Script

function CalculateAge(sender, args) {
                    // Get DOB Date
                    var DOB = args.get_newDate();
                    var DOBM = DOB.getMonth() + 1;
                    var DOBD = DOB.getDate();
                    var DOBY = DOB.getFullYear();
                    // Get Current Date
                    var currentTime = new Date()
                    var CM = currentTime.getMonth() + 1
                    var CD = currentTime.getDate()
                    var CY = currentTime.getFullYear()
                    var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                   
                    var firstDate = new Date(CY, CM, CD); // Current Date
                    var secondDate = new Date(DOBY, DOBM, DOBD); // DOB Date
                    var diffDays = Math.ceil((firstDate.getTime() - secondDate.getTime()) / (oneDay));
                    var birthDate = new Date(DOBM + '/' + DOBD + '/' + DOBY); // mm/dd/yyyy
                    currentDate = new Date();
                    // one year calculation
                    var perYear = 24 * 60 * 60 * 1000 * 365.25;
                    if (diffDays < 31) {
                        age = Math.round(diffDays / 1); // Calculate Days
                        $find('<%=txtAge.ClientID %>').set_value(age);
                        document.getElementById('<%=ddlYears.ClientID %>').value = "Days(s)";
                    }
                    else if (diffDays < 365) {
                    age = Math.round(diffDays / 30); // Calculate Months
                    $find('<%=txtAge.ClientID %>').set_value(age);
                    document.getElementById('<%=ddlYears.ClientID %>').value = "Month(s)";
                    }
                    else if (diffDays > 365) {
                    var age = Math.round((currentDate.valueOf() - birthDate.valueOf()) / perYear); // Calculate Years
                    $find('<%=txtAge.ClientID %>').set_value(age);
                    document.getElementById('<%=ddlYears.ClientID %>').value = "Year(s)";
                    }
                }

No comments:

Post a Comment