首页 > 解决方案 > 如何计算年、月和日的年龄

问题描述

这是我的代码:

<?php 

            $userDob = $result['DoB'];

            //Create a DateTime object using the user's date of birth.
            $dob = new DateTime($userDob);

            //We need to compare the user's date of birth with today's date.
            $now = new DateTime();

            //Calculate the time difference between the two dates.
            $difference = $now->diff($dob);

            //Get the difference in years, as we are looking for the user's age.
            $age = $difference->y;

            //Print it out.
            echo $age;

            ?>

我想输出 50 Years, 6 Months, 20 Days 但我不知道如何准确地说出来,因为这种方法只输出年数。

标签: php

解决方案


是的,php为此内置了一些东西:)

$age_check = "$day-$month-$year";
$today = date("Y-m-d");
$calculate = date_diff(date_create($age_check),date_create($today));
$age = $calculate->format('%y');

推荐阅读