...

View Full Version : please help with "date of birth" to "age" calculation



LordMerlin
01-19-2006, 11:12 AM
Hi everyone.

I'm trying to incorporate a date of birth to age calculator on my site. Currently I have the following Date Validation Script (http://www.smartwebby.com/DHTML/date_validation2.asp) which validates the date of birth to make sure it's in the dd/mm/yyyy format.

Then, I have the following piece of code, which calculates the age, according to the date of birth



<script language="javascript" type="text/javascript">
<!--
function calc(form) {
var today= new Date();
var birthday= new Date(document.form1.dob.value);
secold=(today.getYear()-birthday.getYear())*31557600+(today.getMonth()-birthday.getMonth())*2629800+(today.getDay()-birthday.getDay())*86400+today.getHours()*3600+today.getMinutes()*60+today.getSeconds()

document.form1.age.value=Math.floor(((secold/3600)/24)/365.25);
}
//-->
</script>


My problem is, this age calculator expects the date format to be mm/dd/yyyy. Is there a way of specifying that my date in the the format of dd/mm/yyyy?

MRMAN
01-19-2006, 11:29 AM
One thing you could do is it split the data into the different sections then join them back up into the american format.

i.e.


$splitdate = birthday.split("/")

$american_date = $splitdate[1]+"/"+$splitdate[0]+"/"+$splitdate[2]

felgall
01-19-2006, 10:05 PM
Here's a shorter way to do it that does both the validation of the date format and the age calculation all at once. The getYear method that your code uses returns different values in different browsers because it is NOT Y2K compliant, the following code doesn't have that problem because it compares the dates directly.


<script language="javascript" type="text/javascript">
function calc(form1) {
var bd = form1.dob.value;
var re = /^(0?[1-9]|[12][0-9]|3[01])\/(0?[1-9]|1[0-2])\/(19|20)\d{2}$/;
if (!re.test(bd)) {alert('Birthday must be dd/mm/ccyy format'); return;}
$sd = bd.split("/")
var today= new Date();
var birthday= new Date(sd[2],sd[1],sd[0]);
var age = today - birthday;
form1.age.value=Math.floor(((age/3600)/24)/365.25);
}
</script>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum