如何在PHP中计算日期(计算年龄)(日期存储在Unix时间中)


How to calculate the dates (calculate age) in PHP (dates are stored in Unix Time)?

有必要

根据出生日期计算年龄。有关出生日期的信息以Unix时间存储在数据库中。

我不懂PHP,才刚刚开始编辑我现有的代码以获得我需要的东西。

例:

$tpl->set( '{birthday}', langdate( "D M Y", $row['birthday'] ) );

CMS 标记 {birthday} 中显示出生日期,从数据库的行生日中获取 Unix 时间值,并转换为清晰的视图"D了 Month Y耳朵"。

我想在CMS标签{age}中创建可用,并通过他发布年龄。

我想是这样的:

$tpl->set( '{age}', current date - $row['birthday'] ) );

但是怎么做 - 不知道...

<?php
$now = strtotime(date('Y-m-d')); // Today in UNIX Timestamp
$birthday = strtotime(date('D M Y', strtotime($row['birthday']))); // Birthday in UNIX Timestamp
$age = $now - $birthday; // As the UNIX Timestamp is in seconds, get the seconds you lived
$age = $age / 60 / 60 / 24 / 365; // Convert seconds to years
echo floor($age); // Round down to whole integer and echo it
?>
在我看来,这是用日期计算的最

简单方法,因为它很容易用秒计算。不需要太多使用大脑:)

但更美丽的方式是:

<?php
$birthday = new DateTime($row['birthday']);
$now = new DateTime();
$age = $now->diff($birthday);
echo $age -> y;
?>

您可以在查询中使用

SELECT .. TIMESTAMPDIFF(YEAR, FROM_UNIXTIME(dob), NOW()) as AGE ..

这对

我有用

echo date("Y", time()) - date("Y", $birth_in_unix_format);