user2180590
user2180590

Reputation: 1

Calculate age from birthdate in PHP

A friend of mine gave me this code, but I can't seem to get it to work. It keeps telling me that I have an undefined variable, but I have tried to define it several different ways, but it doesn't show their right age, it shows everyone as 43. Here is the code I'm using:

$bdate= getdate('$_GET["bd"]');

if($bdate == 0){ $nodate = 1; }
$bdate = strtotime( $bdate );
$birthday = date("n/j/Y",$bdate);  //must be as m/d/yyyy

$bday = explode("/", $birthday); //parse
$b_mm = $bday[0]; //birthday month
$b_dd = $bday[1]; //birthday day
$b_yyyy = $bday[2]; //birthday year

//compare timestamps of mm/dd for birthday and today
$bday_mm_dd = mktime(0,0,0,$b_mm,$b_dd,0);
$today_mm_dd = mktime(0,0,0,date("m"),date("d"),0);
$age = date("Y", time()) - $b_yyyy;

if ($bday_mm_dd > $today_mm_dd) {
//birthday hasnt happened yet this year
$age = $age - 1;
}

Just for clarification in my sql statement I have the birthdate listed as bd.

If anyone can help, I would greatly appreciate it.

Upvotes: 0

Views: 1362

Answers (1)

pilcrow
pilcrow

Reputation: 58741

getdate() returns an associative array, not a textual representation of a date. strtotime() can't make sense of this, and your first call to date() then interprets its timestamp argument as zero, the UNIX epoch.

Guess how many years ago the epoch was? :)

Skip strtotime() and just pass $bdate[0] to date(). That will contain the epoch timestamp representation of 'bd'.

Upvotes: 1

Related Questions