Tuesday, October 6, 2009

JScript birth date madness

I had an earlier post on calculating a birth date in VBScript, but the IIR form was already set in java script which lacks a “datediff” function to calculate an age. It shouldn’t have been all that difficult to calculate just using date math, but there is a conversion issue when trying to use a date field in place of a string as the birth date source.

The issue is the use of ISO8601 format of YYYY-MM-DD versus the entry format of MM-DD-YYYY. The solution is to parse the string before doing the math. A complete "age" functions is as follows:

if (eventObj.IsUnDoRedo)
{
return;
}

//==============================================
//= On date of birth changed calculate age in years and set age field
//==============================================

var DOB = XDocument.DOM.selectSingleNode("my:myFields/my:DateOfBirth");

if ((DOB != null) && (DOB.text != ""))
{
var myStringList = DOB.text.split('-');
var DOBText = myStringList[1]+'/'+myStringList[2]+'/'+myStringList[0];

var dt1 = new Date();
var dt2 = new Date(DOBText);

var years = dt1.getFullYear() - dt2.getFullYear();

// Check to see if it's before or after this years birthday
dt2.setYear(dt1.getFullYear());

if (dt1 <>
{
years--;
}
SetField("Age",years);
}
}