Forum Moderators: coopster

Message Too Old, No Replies

Age Calculation

Doesn't work - any ideas?

         

Darylt

7:01 pm on Jul 31, 2008 (gmt 0)

10+ Year Member



I have used the code below to calculate a persons age, however it dosent correct the age for people who havent had their birthday yet.

Can anyone see what is wrong?

<?php
function DetermineAgeFromDOB ($YYYYMMDD_In)
{
// Parse Birthday Input Into Local Variables
// Assumes Input In Form: YYYYMMDD
$yIn=substr($YYYYMMDD_In, 0, 4);
$mIn=substr($YYYYMMDD_In, 4, 2);
$dIn=substr($YYYYMMDD_In, 6, 2);

// Calculate Differences Between Birthday And Now
// By Subtracting Birthday From Current Date
$ddiff = date("d") - $dIn;
$mdiff = date("m") - $mIn;
$ydiff = date("Y") - $yIn;

// Check If Birthday Month Has Been Reached
if ($mdiff < 0)
{
// Birthday Month Not Reached
// Subtract 1 Year From Age
$ydiff--;
} elseif ($mdiff==0)
{
// Birthday Month Currently
// Check If BirthdayDay Passed
if ($ddiff < 0)
{
//Birthday Not Reached
// Subtract 1 Year From Age
$ydiff--;
}
}
return $ydiff;
}
?>

LifeinAsia

7:16 pm on Jul 31, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Um, doesn't PHP have a simple function to compute the difference between 2 dates directly without all this?

Darylt

7:49 pm on Jul 31, 2008 (gmt 0)

10+ Year Member



Not that I can find

cameraman

7:54 pm on Jul 31, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This one was fun. Try this out:

preg_match('#(\d{4})(\d{2})(\d{2})#',$YYYYMMDD_In,$parts);
$birth = strtotime("{$parts[1]}-{$parts[2]}-{$parts[3]}");
$seconds = time() - $birth;
$age = (int) ($seconds / 31557600.0);

The first line extracts the date parts from the format you want to use. The second turns it into a timestamp. Then we subtract it off of today's timestamp and divide by the number of seconds in a year (including 1/4 day per year to account for leap years).

Darylt

8:15 pm on Jul 31, 2008 (gmt 0)

10+ Year Member



I was using the following to call my function

<?php require("age.php"); ?>

<?php
// Example Age Input
$DateOfBirth=$row_member_profile['handler_dob'];

// Calculate Age Using Function:
$Age= DetermineAgeFromDOB ($DateOfBirth);

// Display Results
echo $Age ;
?>

what would I use for yours?

[edited by: Darylt at 8:17 pm (utc) on July 31, 2008]

cameraman

8:23 pm on Jul 31, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just replace the content of your DetermineAgeFromDOB function with what I posted, and add the line:
return $age;
to the bottom.

LifeinAsia

10:29 pm on Jul 31, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Not that I can find

Really? That's bizarre- it seems like that would be a common function.

coopster

2:52 pm on Aug 1, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Calculate age [webmasterworld.com]