. . Hong Kong Business Software Company
Expert in web-based solutions
Software House in Hong Kong

Microsoft Certified Solution Developer

 

Chief Architect's Blog on software development

13 January 2009
Convert DOB to Age with month accuracy
In a Course Administration System for an education center, I was asked to convert Date of Birth to Age with month accuracy. The reason is that students of that education center are very young (some of them are below 1 year old). This does not seem to be very difficult on the first sight. However, you need to know exactly the requirement of your client before you create a conversion function. At first, I thought the client want to round the result to the nearest month (i.e. if today is 13 January 2009 and the student birthday is 14 December 2007, I treat it as 1 year 1 month old because it is the nearest result, but the client expects the result should be 1 year 0 month old!).  My javascript function is as follows:

function toAge(birthdayTextBox, outputTextBox)
{
	var str;
	var aDate = new Date(birthdayTextBox.value);
	var thisDate= new Date();
	var y;
	var m;
	var d;
	try
	{
		y = thisDate.getFullYear() - aDate.getFullYear();
		m = thisDate.getMonth() - aDate.getMonth();
		d = thisDate.getDate() - aDate.getDate();
		if (d < 0) {
		    m = m - 1;
		}
         		if (m < 0)
            	{
                	    m = m + 12;
                	    y = y - 1;
            	}
            	str= y + "yr" + m + "mth";
	}catch (e)
		{
		    str = '';
		}

	if (str == 'NaNyrNaNmth')
	{ str = ''; }
	outputTextBox.value = str;
}
Testing:
Date of Birth:

OTHER RELATED BLOGS