Jump to content

Convert a date of birth to age


stevenjweir

Recommended Posts

Hi all,

 

I'm having a bit of trouble a script running on a site where it converts a date of birth in a database shown like this '30/04/1993' to an actual age, for instance 18 in this case. Only the script I'm using below shows this age as 17, not 18 as it should be.

 

<?php
  $birthday = $row_getdets['dob']; 
   function birthday ($birthday){
   list($day,$month,$year) = explode("/",$birthday);
   $day_diff   = date("d") - $day;
   $month_diff = date("m") - $month;
   $year_diff  = date("Y") - $year;
   if ($day_diff < 0 || $month_diff < 0)
     $year_diff--;
   return $year_diff;
 }
?>

 

So i've tried to remedy this myself with the following:

 

<?php
$birthday = $row_getdets['dob'];
function birthday ($birthday){
  	list($year,$month,$day) = explode("/",$birthday);
   	$year_diff  = date("Y") - $year;
   	$month_diff = date("m") - $month;
   	$day_diff   = date("d") - $day;
   	if ($month_diff < 0) $year_diff--;
else if (($month_diff==0) && ($day_diff < 0)) $year_diff--;
return $year_diff;
 }
?>

 

..but I'm having a syntax error (unexpected T_LINE), most probably down to my novice ability, I bet I've missed something simple. I'm still learning guys and I'd really appreciate any help at all.

Link to comment
https://forums.phpfreaks.com/topic/247940-convert-a-date-of-birth-to-age/
Share on other sites

Works for me.

 

<?php

$birthdate = '1992/04/19';
// $birthdate = '1992/10/23';
// $birthdate = '1992/09/26';
// $birthdate = '1992/09/27';
// $birthdate = '1992/09/28';

function getAge($dob)
{
    list($year, $month, $day) = explode('/', $dob);
    
    $years  = date('Y') - $year;
    $months = date('m') - $month;
    $days   = date('d') - $day;
    
    if ($months < 0 || ($months == 0 && $days < 0))
        $years--;
    
    return $years;
}

echo getAge($birthdate);

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.