简体   繁体   中英

Calculate age In Years and Days PHP

I know this has been asked many times over the years, but I still get different results than what I think should be right. I have the following code that calculates the amount of days between two dates and then it converts it to years and days. When I convert result isn't what I expect. See below. Please let me know what is incorrect, this is really frustrating.

Thanks!

$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 />";

What I want to appear: Age: 35y-0d

But what I get: Age: 35y-9d

Because leap years contains 366 days you can't just divide days/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 ";

Here you can try live PHP code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM