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

01-19-2006, 12:12 PM
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);


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?

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


$splitdate = birthday.split("/")

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

01-19-2006, 11: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;

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum