i have a database which compare birthdate of a person to current date to get age of the person at given time.
i use the following code to convert them into age
$datetime_date = date("d-m-Y");
$time_diff = abs(strtotime($datetime_date) - strtotime($birthdate));
$years = floor($time_diff / (365*60*60*24));
$months = floor(($time_diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($time_diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
if ($years > 0) {$new_age = "$years year $months month";}
elseif (($years == 0) && ($months > 0)) {$new_age = "$months month $days day";}
elseif (($years == 0) && ($months == 0)) {$new_age = "$days day of life";}
i have saved the age in the database as: (number) year (number) month OR (number) month (number) days OR (number) days
currently, i would like to group them into agegroup, so i would need to convert them back into numbers for comparison
eg: group age < 1 year group age 1-12 years group age 12-60 year etc
can someone advice how to convert a age (in time period) back into numberical format or unix format for easy comparison?
You can convert the fields back to seconds
$new_age_split = explode(" ",$new_age);
if ($new_age_split[1] == 'year')
{
$age = (($new_age_split[0] * 365) + ($new_age_split[2] * 30) + $new_age_split[4]) * 24*60*60
}
else
{
if ($new_age_split[1] == 'month')
{
$age = (($new_age_split[0] * 30) + $new_age_split[2] ) * 24*60*60
}
else
if ($new_age_split[1] == 'day')
{
$age = ($new_age_split[0]) * 24*60*60
}
Then you can use the new DateTime(date("U") - $age)
or date_create(date("U") - $age)
depending on what you need to do with the output
Use the DateTime
and DateInterval
classes; they make your task easier:
$birthdate = new DateTime('1997-09-14');
$today = new DateTime('now');
$diff = $today->diff($birthdate);
echo('Age: '.$diff->y."
");
print_r($diff);