Neil McDonald's Dynamics 365 Blog

Set age based on date of birth

with one comment

Dob_js

I had a requirement to set an ‘Age’ attribute based on the contents of the Date of Birth field on Contacts. The below script in the On Save, On Load or On Change will do this.

Note: You will need to change the “birthdate” and “new_age” field names to the relavant fields on your form.

CRM 2011


function calcBirthday() {
if(Xrm.Page.getAttribute("birthdate").getValue() != null)
{
var now = new Date(); //get today's date
var birthday = Xrm.Page.getAttribute("birthdate").getValue(); //get the dob value
var diff = now.getMonth() - birthday.getMonth();  //have they had their birthday already this year?
var age; //use to store age

if (diff == 0) //if birthday is this month, compare the days instead
{
diff = now.getDate() - birthday.getDate();
}

if(diff > -1) //if they've had a birthday this year
{
age = now.getFullYear() - birthday.getFullYear();
}
else //if they have not had a birthday yet this year
{
age = now.getFullYear() - birthday.getFullYear() - 1;
}

Xrm.Page.getAttribute("new_age").setValue(age.toString()); //set the new_age attribute
}
}

CRM 4


function calcBirthday(){
if(crmForm.all.birthdate.DataValue != null)
{
var now = new Date(); //get today's date
var birthday = crmForm.all.birthdate.DataValue; //get the dob value
var diff = now.getMonth() - birthday.getMonth();  //have they had their birthday already this year?
if (diff == 0) //if birthday is this month, compare the days instead
{
diff = now.getDate() - birthday.getDate();
}

if(diff > -1) //if they've had a birthday this year
{
var bd1 = now.getFullYear() - birthday.getFullYear();
crmForm.all.new_age.DataValue =bd1.toString(); //set the new_age attribute
}
else //if they have not had a birthday yet this year
{
var bd2 = now.getFullYear() - birthday.getFullYear() - 1;
crmForm.all.new_age.DataValue =bd2.toString();
}
}
}

Written by neilmcd

Jul 16, 2010 at 11:07 am

Posted in CRM 2011, CRM 4

Tagged with ,

One Response

Subscribe to comments with RSS.

  1. New to Dynamics CRM..
    Where should i insert these codes?
    Thanks.

    adrian

    Aug 2, 2013 at 7:21 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: