PHP中的年龄计算leap年问题 [英] Age calculation leap year issue in php
问题描述
我正在使用以下功能从给定的出生日期开始计算年龄,但是如果使用a年日(即29),则该功能未显示正确的差值.请帮助我修复此代码.
I am using following function to calculate age from given date of birth, but its not showing the correct difference if a leap year day i.e 29 is used. Please help me fix this code.
<?php
function getAbsAge($birthday)
{
list($year,$month,$day) = explode("-", $birthday);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
if ($day_diff < 0 || $month_diff < 0)
{
$year_diff--;
}
if ($year_diff == 0)
{
$interval = date_diff(date_create(), date_create($birthday));
$months = $interval->format("%M");
$days = $interval->format("%d");
if ($months > 0)
{
return $interval->format("%M Months %d Days");
}
else if ($months == 0 && $days > 1)
{
return $interval->format("%d Days");
}
else
{
return $interval->format("%d Day");
}
}
else if ($year_diff == 1)
{
return "$year_diff Year";
}
else if ($year_diff > 1)
{
return "$year_diff Years";
}
}
echo getAbsAge("2012-02-29")
?>
如果有人可以提出更好的代码,请对其进行更新.
Also if anyone can suggest a better code then please update it.
如果一个人不到1岁,我需要以几个月和几天为单位查找出生日期.
I need to find date of birth in months and days if a person is less than 1 year old.
我的服务器上安装了最新的5.4 php版本.
I am having latest 5.4 php version on my server.
2012年2月29日,它返回2年,而应该是3年.请帮忙.
With 2012-02-29, its returning 2 Years whereas it should be 3 Years. Please help.
推荐答案
为什么不一直使用date_diff()
函数?它会给您想要的结果:
Why are you not using the date_diff()
function all the way through? it will give you the desired result:
function getAbsAge($birthday) {
$age = '';
$diff = date_diff(date_create(), date_create($birthday));
$years = $diff->format("%y");
$months = $diff->format("%m");
$days = $diff->format("%d");
if ($years) {
$age = ($years < 2) ? '1 Year' : "$years Years";
} else {
$age = '';
if ($months) $age .= ($months < 2) ? '1 Month ' : "$months Months ";
if ($days) $age .= ($days < 2) ? '1 Day' : "$months Days";
}
return trim($age);
}
另一种方法是通过计算以秒为单位的时间差,然后从那里获取时间差:
Another way would be by calculating the time difference in seconds and taking it from there:
list($year,$month,$day) = explode("-", $birthday);
$diff = mktime(0,0,0,date('n'),date('j'),date('Y')) - mktime(0,0,0,$month,$day,$year);
然后一天是24小时,每个60分钟,又是60秒:
Then a day consists of 24 hours each with 60 minutes each with 60 seconds:
$sday = 60 * 60 * 24;
然后计算年差为:
$years = floor($diff / (365.2425 * $sday));
但是我只会坚持使用date_diff()
这篇关于PHP中的年龄计算leap年问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!