PHP calculate age with birthtime (Y-m-d\TH:i:sO)

1.8k views Asked by At

I'm trying to calculate an age in php, but just want to increase the age if the birthtime is also reached, not only the birthday date. Here is what I got so far:

$today = date("Y-m-d\TH:i:sO");
$bday = "1987-01-01T15:30:00+0200";
$diff = abs(strtotime($bday) - strtotime($today));
$age = floor($diff / (365*60*60*24));

It works if the day is reached, but is not time-sensitive. I appreciate any help!

1

There are 1 answers

3
Qaisar Satti On
 # object oriented
    $from = new DateTime('1987-01-01 T15:30:00+0200');
    $to   = new DateTime('today');
    echo 'Years '.$from->diff($to)->y; echo '<br/>';
    echo 'Month '.$from->diff($to)->m; echo '<br/>';
    echo 'Days '.$from->diff($to)->d; echo '<br/>';
    echo 'Hours '.$from->diff($to)->h; echo '<br/>';

    # procedural
    echo date_diff(date_create('1987-01-01 T15:30:00+0200'), date_create('today'))->y;


<?php

//Convert to date
$datestr="2015-06-11 19:10:18";//Your date
$date=strtotime($datestr);//Converted to a PHP date (a second count)

//Calculate difference
$diff=$date-time();//time returns current time in seconds
$days=floor($diff/(60*60*24));//seconds/minute*minutes/hour*hours/day)
$hours=round(($diff-$days*60*60*24)/(60*60));

//Report
echo "$days days $hours hours remain<br />";
?>