function calculateAge(executionContext) {
var formContext = executionContext.getFormContext();
var birthDateAttr = formContext.getAttribute("birthdate"); // Birthdate field logical name
var ageAttr = formContext.getAttribute("new_age"); // Age field logical name
if (!birthDateAttr || !ageAttr) return;
var birthDate = birthDateAttr.getValue();
if (!birthDate) {
ageAttr.setValue(null);
return;
}
var today = new Date();
var age = today.getFullYear() - birthDate.getFullYear();
// adjust if birthday hasn’t occurred yet this year
if (
today.getMonth() < birthDate.getMonth() ||
(today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
) {
age--;
}
ageAttr.setValue(age);
}
Calculate Age from Birthdate and set it into Age whenever the form loads or Birthdate changes
Published inDynamics CRM