Tags

, , ,

Hii,

This is again a very common requirement from the Customers; Automatic Calculation of Age on birth-date.

I’m writing this blog to clear the difference between two date functions which confused me for a while.

  • getFullYear() – Returns the year in four digits. (2013 -> 2013)
  • getYear() – Returns the year from 1900-1999 in two digits eg (1988 -> 88) and from 2000 till next in four digits. 

Earlier I was using getYear() which was giving me unexpected results, after Debugging only I came to know the reason behind.
Later, instead of getYear() when I used getFullYear(), the result was satisfying.

The J-Script code which I’m Using to calculate the Age on Birth-date is:

function Age() {
if(Xrm.Page.getAttribute("new_dateofbirth").getValue() != null)
{
var DOB = Xrm.Page.getAttribute("new_dateofbirth").getValue();
var Today = new Date();
Today.setHours(0, 0, 0, 0);
var db = 0;
if(DOB > Today )
{
alert("Please Enter Genuine BirthDate !!!");
Xrm.Page.getAttribute("new_dateofbirth").setValue(null);
}
else
{
db = Today.getFullYear() - DOB.getFullYear();
var x = Today.getDate() ;
var y = DOB.getDate() ;
var a = Today.getMonth() + 1;
var b = DOB.getMonth() + 1;
if((a < b) || (a==b & x < y))
db=db - 1;
}
Xrm.Page.getAttribute("new_age").setValue(db);
}
}

Sometimes these small issues do spin your head around for a day. Hope this was helpful.

Thanks !!!
🙂