I could not find how to calculate current age from Date of
Birth ( DOB ) on the internet so I have decided to write this post to help others with the same
requirement.
function CalculateAge()
{
if(Xrm.Page.getAttribute("birthdate").getValue() != null)
{
var now = new Date();
var birthday = Xrm.Page.getAttribute("birthdate").getValue();
var monthdif = now.getMonth() - birthday.getMonth();
var nowyear = Xrm.Page.getAttribute("birthdate").getValue().getFullYear();
if(monthdif > -1)
{
Xrm.Page.getAttribute("new_age").setValue(now.getFullYear() - birthday.getFullYear());
}
else
{
Xrm.Page.getAttribute("new_age").setValue(now.getFullYear() - birthday.getFullYear()-1);
}
}
}
How it works,
If the contact has already had their birthday this year, you
simply subtract the year of birth from the current year. If they have not yet have their birthday, you
will need to subtract 1 from the above sum.
I also used getFullYear() and not getYear() as this uses
YYYY instead of YY. For example, 1984
instead of 84. Using getYear(), if you
enter a date before 2000 you will get strange results.
A big thank you to Neil McDonald @ http://xrmrocks.com/?tag=calculateage whose Dynamics CRM 4 solution I used to create the following.
No comments:
Post a Comment