如何计算年,月和日的年龄[重复]

问题描述 投票:0回答:1

这是我的代码:

<?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年,6个月,20天之类的内容,但我不知道如何准确地表达它,因为此方法仅输出年数。

php
1个回答
0
投票

是的,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');
© www.soinside.com 2019 - 2024. All rights reserved.