Reputation: 81
I am aware this is done using a javascript library. Currently, the only examples I've found for CRM 2011 involve calculating the age in years only using this code:
function CalcAge()
{
var now = new Date(); //Todays Date
var birthday = Xrm.Page.getAttribute("birthdate").getValue(); //Get the Date of Birth value
var diff = now.getMonth() - birthday.getMonth(); //Check to see if Birthday has already passed
if (diff > -1) //If Birthday has already occurred
{
var bd1 = now.getFullYear() - birthday.getFullYear();
//set the age attribute
Xrm.Page.getAttribute("frc_age").setValue(bd1.toString());
}
else //If Birthday has not already occurred
{
var bd2 = now.getFullYear() - birthday.getFullYear() - 1;
Xrm.Page.getAttribute("frc_age").setValue(bd2.toString());
}
}
I need help implementing a similar function that also accounts for the months.
-Thank You
Upvotes: 0
Views: 5319
Reputation: 2123
you can try below code if DOB is in format "MM/dd/yyyy". You can also change it for other formats accordingly.
var now = new Date(); //Todays Date
var birthday = Xrm.Page.getAttribute("birthdate").getValue();
birthday=birthday.split("/");
var dobMonth= birthday[0];
var dobDay= birthday[1];
var dobYear= birthday[2];
var nowDay= now.getDate();
var nowMonth = now.getMonth() + 1; //jan = 0 so month + 1
var nowYear= now.getFullYear();
var ageyear = nowYear - dobYear;
var agemonth = nowMonth - dobMonth;
var ageday = nowDay- dobDay;
if (agemonth <= 0) {
ageyear--;
agemonth = (12 + agemonth);
}
if (nowDay < dobDay) {
agemonth--;
ageday = 30 + ageday;
}
var val = ageyear + "-" + agemonth + "-" + ageday;
return val;
you can also use some of below:
Simple age calculator in JavaScript
How can I calculate the number of years betwen two dates?
Upvotes: 1