Calculate age based on date of birth
Solution 1:
PHP >= 5.3.0
# 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;
demo
functions: date_create()
, date_diff()
MySQL >= 5.0.0
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age
demo
functions: TIMESTAMPDIFF()
, CURDATE()
Solution 2:
Very small code to get Age:
<?php
$dob='1981-10-07';
$diff = (date('Y') - date('Y',strtotime($dob)));
echo $diff;
?>
//output 35
Solution 3:
Got this script from net (thanks to coffeecupweb)
<?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);
?>
Solution 4:
Reference Link http://www.calculator.net/age-calculator.html
$hours_in_day = 24;
$minutes_in_hour= 60;
$seconds_in_mins= 60;
$birth_date = new DateTime("1988-07-31T00:00:00");
$current_date = new DateTime();
$diff = $birth_date->diff($current_date);
echo $years = $diff->y . " years " . $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $months = ($diff->y * 12) + $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $weeks = floor($diff->days/7) . " weeks " . $diff->d%7 . " day(s)"; echo "<br/>";
echo $days = $diff->days . " days"; echo "<br/>";
echo $hours = $diff->h + ($diff->days * $hours_in_day) . " hours"; echo "<br/>";
echo $mins = $diff->h + ($diff->days * $hours_in_day * $minutes_in_hour) . " minutest"; echo "<br/>";
echo $seconds = $diff->h + ($diff->days * $hours_in_day * $minutes_in_hour * $seconds_in_mins) . " seconds"; echo "<br/>";