How to take out user's AGE in PHP?

laksh_khamesra

New Member
This code i have made to take out age of the user(the date in the mktime is just for testing). But many problems are occurring like if the user was born on 2nd of a month today is 1st of a month then the date comes in minus (-) which makes it too confusing... After all, i m completely stuck & confused. Please tell how to take out users age.

PHP:
$td = mktime(0,0,0,05,24,1991);
$td1 = time();

$aa = date("Y", $td);
$bb = date("Y", $td1);
$age = $bb - $aa;

$cc = date("m", $td);
$dd = date("m", $td1);
$month = $dd - $cc;

$ee = date("d", $td);
$ff = date("d", $td1);
$days = $ff - $ee;

echo "$age years, $month months and $days days";
 

durrban

New Member
Your syntax appears correct. You just need to take out the negative sign or you need the absolute value. Luckily, php comes with tons of handy math functions at your disposal and unfortunately, you only need one. abs() is the function.

Code:
[B]$days = abs($ff - $ee);[/B]

you might want to do this with all of them or you will have the same problem when the wrong time of the year rolls around.

Cheers,
Jonathan
 

Erni

New Member
no, abs() will not show up the correct answer.
Calculations must be performed more carefuly and step by step.
Try to kick this:
$d1 = array(2008,6,15);
$d2 = array(1998,5,21);

$days = $d1[2] - $d2[2];
if($days <= 0)
{
// we should add the quantity of days in the month
$days += date("d",mktime(0,0,0,$d1[1],$d1[2],$d1[0]));
$d1[1]--;
}
$months = $d1[1] - $d2[1];
if($months <= 0)
{
$months += 12;
$d1[0]--;
}
$age = $d1[0] - $d2[0];


echo "$age years, $months months and $days days";
 
Top