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
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);

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.