0

我有一个$dob返回日期的变量,格式如下:1970-02-01 00:00:00

如何使用php计算人的年龄?

4

6 回答 6

5

您的问题在PHP 文档中有详细解释,基本上是这样的:

// create a datetime object for a given birthday
$birthday = new DateTime("2012-12-12");
// substract your timestamp from it
$diff = $birthday->diff($dob);

// output the difference in years
echo $diff->format('%Y');
于 2013-10-05T20:56:24.610 回答
4

尝试这个:

<?php

$age = '1970-02-01 00:00:00';

echo (int)((time()-strtotime($age))/31536000);

输出:43,以年为单位。

于 2013-10-05T20:53:44.660 回答
0

单线:

echo date_create('1970-02-01')->diff(date_create('today'))->y;

演示

于 2013-10-06T11:44:36.367 回答
0
$dob = '1970-02-01 00:00:00';

$date = new DateTime($dob);
$diff = $date->diff(new DateTime);

echo $diff->format('%R%a days');

基本上是从这里偷来的:http: //uk1.php.net/manual/en/datetime.diff.php

格式化选项:http ://uk1.php.net/manual/en/dateinterval.format.php

于 2013-10-05T21:04:07.673 回答
-1

strtotime() 会将您的日期转换为时间戳,然后从 time() 开始,结果是以秒为单位的年龄。

$age_in_seconds = time() - strtotime('1970-02-01');

要以年为单位显示年龄(+- 1 天),然后除以一年中的秒数:

echo "Age in whole years is " . floor($age_in_seconds / 60 / 60 / 24 / 365.25);

于 2013-10-05T21:04:18.390 回答
-1

我会试试这个

$user_dob = explode('-',$dob);
$current_year= date('Y');
$presons_age = $current_year - $user_dob[0];

这是一个未经测试的代码,但我觉得你应该得到逻辑。

于 2013-10-05T20:55:55.170 回答