用PHP计算年龄



我知道这些年来人们问了很多次这个问题,但我仍然得到了与我认为应该正确的结果不同的结果。我有下面的代码,它计算两个日期之间的天数,然后将其转换为年和天。当我转换结果并不是我所期望的。请参见下文。请让我知道什么是不正确的,这真的很令人沮丧。

谢谢!

$born = '1985-09-09';
$date = date('Y-m-d H:i:s'); // this is today's date
$birthdate = new DateTime("$born");
$today = new DateTime("$date");
$diff = $today->diff($birthdate)->format("%a");
$days = $diff;
$years_remaining = intval($days / 365); //divide by 365 and throw away the remainder
$days_remaining = $days % 365;    
echo "<b>Age:</b> ".$years_remaining."y-".$days_remaining."d<br />";

我想要出现的内容:年龄:35y-0d

但我得到的是:年龄:35y-9d

因为闰年包含366天,所以不能只划分天数/365:

<?php
$born = '1985-09-05';
$date = date('Y-m-d H:i:s'); // this is today's date
$birthdate = new DateTime("$born");
$today = new DateTime("$date");
// get diff in full years
$diff_years = $today->diff($birthdate)->format("%y");
// add years diff to birthday, (so here your last birthday date)
$birthdate->add(new DateInterval("P{$diff_years}Y"));
// count days since your last birthday party day
$diff_days = $today->diff($birthdate)->format("%a");
echo "Age: ".$diff_years."y and ".$diff_days." days ";

在这里你可以尝试实时PHP代码

最新更新