PHP用出生时间计算年龄(Y-m-d \ TH:i:sO)

时间:2015-06-09 15:58:42

标签: php date datetime strtotime

我试图在php中计算年龄,但只想在达到出生时间时增加年龄,而不仅仅是生日日期。这是我到目前为止所得到的:

$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));

如果达到了这一天,它会起作用,但对时间不敏感。我感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

 # 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 />";
?>