we have already explained how you can get age from provide date now will focus more on how to validate date of birth today
now this function is basically validate date and finds the age from date_diff function in php
We are going to use the function we applied in date validation in How to do date validation in php (special function)
The simple function that does the work
then we apply a little tweak to get what we want
this function makes sure that the date parameters are integers
<?php
function get_age($date){
$dateparameters = array();
$date = preg_replace("/[^0-9\']/", ",", $date);
$date = explode(',', $date);
$age = '';
if(count($date) == 3){
for ($i = 0; $i < 3; ++$i) {
$dateparameters []= $date[$i];
}
$year = $dateparameters[0];
$month = $dateparameters[1];
$actualmonth = $dateparameters[1];
$actualday = $dateparameters[2];
$actualdate = $year.'-'.$month.'-'.$actualday;
$day = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$day = range(1, $day); // day range
$month = range(1, 12); // month range
if(in_array($actualday, $day) && in_array($actualmonth, $month)){ //Check if actual month and day is in range of days that should be in the provided month of the given year
$origin = date_create($actualdate); // create the date of birth in proper date parameters
$target = date_create(date('Y-m-d')); // creates the current day from the user is calculating from
$age = date_diff($target, $origin);
$age = intval($age->format('%y'));
}
}
return $age;
}
?>
HOW TO APPLY IT
let’s apply this in our work
you can echo this function since it just integer that is expected from it
we can still program a logic to check if it empty or not
<?php
$birthdate = '2016-10-29';
if(!empty(get_age($birthdate))){
echo 'since you are born in '.$birthdate.' your age is: <b>'. get_age($birthdate).' years</b> Older';
}else{
echo $birthdate.' is invalid date of birth';
}
?>