Age Calculation in CRM

function functionName() {
    var CurrentAge = 0;
    var Years = 0;
    if (Xrm.Page.getAttribute("new_dateofbirth") != null && Xrm.Page.getAttribute("new_dateofbirth").getValue() != null && Xrm.Page.getAttribute("new_age") != null) {
        var DateOfBirth = Xrm.Page.getAttribute("new_dateofbirth").getValue();
        var birthDate = new Date(DateOfBirth);
        var todayDate = new Date();
        var todayYear = todayDate.getFullYear();
        var todayMonth = todayDate.getMonth();
        var todayDay = todayDate.getDate();
        var birthYear = birthDate.getFullYear();
        var birthMonth = birthDate.getMonth();
        var birthDay = birthDate.getDate();
        var decrese = false;
        var age = todayYear - birthYear;

        if (todayMonth < birthMonth) {
            age--;
            decrese = true;
        }
        if (birthMonth == todayMonth && todayDay <= birthDay) {
            if (!decrese) {
                age--;
            }
        }
        if (age != undefined && age != null) {
            Xrm.Page.getAttribute("new_age").setValue(age);
            Xrm.Page.getAttribute("new_age").setSubmitMode("always");
        }
    }
}

Comments

Popular posts from this blog

Basic Plugin Code in D365 using C#

CURD (Create, Update, Retrieve and Delete) Operation in D365 using Power Shell Script

Meta Data Using WebApiRequest