如何用PHP显示年龄

时间:2017-02-16 06:26:21

标签: php

我试图通过此代码显示年龄:

$dob =  $entrantInfo['dobYear'].'-'.$entrantInfo['dobMonth'].'-'.$entrantInfo['dobDay'];
$age = date_diff(date_create($dob), date_create('today'))->y;

echo $age;

但是它不起作用,尝试了不同类型的教程,但我仍然遇到麻烦,我该怎么办? 干杯

1 个答案:

答案 0 :(得分:1)

基本示例

$date1 = new DateTime('2011-03-12');
$date2 = new DateTime('2008-03-09');

$diff = $date2->diff($date1);

echo $diff->y;

您的示例

$entrantInfo['dobYear'] = '2011';
$entrantInfo['dobMonth'] = '03';
$entrantInfo['dobDay'] = '12';

$dob =  $entrantInfo['dobYear'].'-'.$entrantInfo['dobMonth'].'-'.$entrantInfo['dobDay']; // Get dynamic date    

$date1 = new DateTime($dob);
$date2 = new DateTime(); // Get current date

$diff = $date2->diff($date1);

echo $diff->y;

请您尝试上面的代码吗?