I'm trying to determine a users exact age, calculated off their birthdate.
I need to be able to tell if they are 1/2 through their current year or not.
Example:
Here's what I currently use for the age calculation function:
$birthday = new DateTime($birthday);
$interval = $birthday->diff(new DateTime);
$age = $interval->y;
Thanks!
Seems like you could just test the m part of the interval.
if ($interval->m >= 6 ) {
// it's $age + 1/2
}
Calculate the exact months in your interval, then divide by 6, truncate, then divide by 2.
/6 + truncate + /2
is like /12
with .0 or .5 only .
<?php
$birthday = new DateTime('08/17/1983');
$interval = $birthday->diff(new DateTime);
$age = floor((($interval->y * 12) + $interval->m) / 6) / 2;
//To display with floating point
echo $age;
echo '<br />';
//To display with "1/2"
echo floor($age) . (fmod($age, 1) == 0.5 ? ' 1/2' : '');
?>
Result: 29.5
and 29 1/2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.