Friday 17 June 2016

PHP - Get age from date of birth


PHP >= 5.3.0

<?php
# object oriented
 $from = new DateTime('1970-02-01');
 $to = new DateTime('today');
echo $from->diff($to)->y;
# procedural
echo date_diff(date_create('1970-02-01'), date_create('today'))->y;
?>
****************************************************


<?php
 /**
* Simple PHP age Calculator
 * * Calculate and returns age based on the date provided by the user.
 * @param date of birth('Format:yyyy-mm-dd').
 * @return age based on date of birth */
 function ageCalculator($dob){
         if(!empty($dob)){
                    $birthdate = new DateTime($dob);
                   $today = new DateTime('today');
                   $age = $birthdate->diff($today)->y;
                   return $age;
         }else{
             return 0;
          }
}
 $dob = '1992-03-18';
echo ageCalculator($dob);
?>
**************************************
<?php
$dob='1981-10-07';
$diff = (date('Y') - date('Y',strtotime($dob)));
echo $diff;
?>
**********************************************************
<?php
function age($birthday){
 list($day, $month, $year) = explode("/", $birthday); 
 $year_diff = date("Y") - $year; 
 $month_diff = date("m") - $month;
 $day_diff = date("d") - $day;
 if ($day_diff < 0 && $month_diff==0)
 $year_diff--; 
if ($day_diff < 0 && $month_diff < 0)
 $year_diff--;
 return $year_diff;
 }
#or the same function that accepts day, month, year as parameters :
function age($day, $month, $year){ 
$year_diff = date("Y") - $year; 
$month_diff = date("m") - $month;
 $day_diff = date("d") - $day; 
 if ($day_diff < 0 && $month_diff==0) 
$year_diff--;
 if ($day_diff < 0 && $month_diff < 0) 
$year_diff--; 
return $year_diff; 
}
#You can use it like this :echo age("20/01/2000");


#which will output the correct age (On 4 June, it's 14).

?> 
**************************************************************
Calculate Age With PHP
Checking dates in PHP can be problematic as PHP primarily concerns itself with date manipulation which revolves around unix timestamps. This is a good thing, mostly. Unix timestamps however, have not concept of leap years, thus it is difficult, though not impossible, to get an accurate date calculation from them. When dates need to be accurate for legal reasons, it is vital that the leap years are considered.

With strtotime()
This first method makes use of the PHP strtotime() function and increments a 1 year on each iteration.


<?php

/*** make sure this is set ***/
date_default_timezone_set('Europe/London');

/**
 *
 * Get the age of a person in years at a given time
 *
 * @param       int     $dob    Date Of Birth
 * @param       int     $tdate  The Target Date
 * @return      int     The number of years
 *
 */
function getAge( $dob, $tdate )
{
        $age = 0;
        while( $tdate > $dob = strtotime('+1 year', $dob))
        {
                ++$age;
        }
        return $age;
}
?>
EXAMPLE USAGE


<?php

/*** a date before 1970 ***/
$dob = strtotime("april 20 1961");

/*** another date ***/
$tdate = strtotime("june 2 2009");

/*** show the date ***/
echo getAge( $dob, $tdate );

?>

Output
48
Using the DateTime Class
The PHP DateTime class allow a little neater code by providing an Object Oriented interface to date functions. By passing a DateInterval object to the DateTime class the DateTime object can be increment 1 year on each iteration until it reaches the target date. The DateTime::add() method requires PHP >= 5.3.


<?php

/*** set the default timezone ***/
date_default_timezone_set('Europe/London');

/**
 *
 * Get the age of a person in years at a given time
 *
 * @param       int     $dob    Date Of Birth
 * @param       int     $tdate  The Target Date
 * @return      int     The number of years
 *
 */
function getAge( $dob, $tdate )
{
        $dob = new DateTime( $dob );
        $age = 0;
        $now = new DateTime( $tdate );
        while( $dob->add( new DateInterval('P1Y') ) < $now )
        {
                $age++;
        }
        return $age;
}

?>
EXAMPLE USAGE
<?php

/*** a date before 1970 ***/
$dob = "April 20 1961";

/*** another date ***/
$tdate = "21-04-2009";

/*** show the date ***/
echo getAge( $dob, $tdate );

?>
Output
48
More DateTime Goodness
Following on with PHP 5.3 and above, the DateTime::diff() method is provided for just this sort of calculation. By using this method, the code is cut down considerably and the calculations done internally.


<?php

/*** dont forget to set this ***/
date_default_timezone_set('Europe/London');

/**
 *
 * Get the age of a person in years at a given time
 *
 * @param       int     $dob    Date Of Birth
 * @param       int     $tdate  The Target Date
 * @return      int     The number of years
 *
 */
function getAge( $dob, $tdate )
{
        $d1 = new DateTime( $dob );
        $d2 = new DateTime($tdate );
        $age = $d2->diff( $d1 );
        return $age->y;
}

?>
EXAMPLE USAGE


<?php

/*** a date before 1970 ***/
$dob = "April 20 1961";

/*** another date ***/
$tdate = "21-04-2009";

/*** show the date ***/
echo getAge( $dob, $tdate );

?>
48
**********************************************************************
<?php 
// PHP 5.3-
function birthday($birthday){ 
    $age = strtotime($birthday);
    
    if($age === false){ 
        return false; 
    } 
    
    list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age)); 
    
    $now = strtotime("now"); 
    
    list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now)); 
    
    $age = $y2 - $y1; 
    
    if((int)($m2.$d2) < (int)($m1.$d1)) 
        $age -= 1; 
        
    return $age; 
} 

echo birthday('1981-05-18'); 

// PHP 5.3+
function birthday($birthday) {
    $age = date_create($birthday)->diff(date_create('today'))->y;
    
    return $age;
}

echo birthday('1981-05-18'); 
?> 

************************************************************
MySQL >= 5.0.0
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age

0 comments:

Post a Comment