从给定的日期时间戳计算年龄 - PHP

时间:2013-10-05 20:51:22

标签: php date

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

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

6 个答案:

答案 0 :(得分:5)

你的问题在PHP documentation,中有详细解释,它基本上是这样的:

// 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');

答案 1 :(得分:4)

试试这个:

<?php

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

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

Output:43岁,多年。

答案 2 :(得分: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

答案 3 :(得分:0)

一衬垫:

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

Demo

答案 4 :(得分:-1)

我会尝试这个

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

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

答案 5 :(得分:-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);

相关问题