March 5, 2013

Calculate age in Microsoft Dynamics CRM 2011

Sometimes inside CRM is necessary to display the actual age of a contact or on a particular date (for example to know how old was the patient when he did a medical exam).

The following code can be used in both situations.
function CalculateAge(birthday, ondate) {
   // if ondate is not specified consider today's date
   if (ondate == null) { ondate = new Date(); }
   // if the supplied date is before the birthday returns 0
   if (ondate < birthday) { return 0; }
   var age = ondate.getFullYear() - birthday.getFullYear();
   if (birthday.getMonth() > ondate.getMonth() || (birthday.getMonth() == ondate.getMonth() && birthday.getDate() > ondate.getDate())) { age--; }
   return age;
}

// example

var birthday = Xrm.Page.getAttribute("new_birthday").getValue();
var age = CalculateAge(birthday);
alert(age);
// age on 1st January 2000, JavaScript Date() object contains months starting from 0
var testdate = new Date(2000, 0, 1, 0, 0, 0);
var testage = CalculateAge(birthday,testdate);
alert(testage);

0 comments:

Post a Comment