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

时间:2015-03-09 00:12:06

标签: php

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

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

示例:

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

显示在CMS标记 {birthday} 中的可用日期,从数据库生日获取Unix时间值并转换为清晰视图" D M Y ear"。

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

我想这样的事情:

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

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

2 个答案:

答案 0 :(得分:1)

您可以使用

在查询中执行此操作

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

答案 1 :(得分:1)

<?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;
?>