我正在计算两个日期的差异:
$date1= $_POST['dob'];
$date2= $_POST['dor'];
$date1 = date_create($date1);
$date2 = date_create($date2);
$diff = $date1->diff($date2);
echo "<p> The difference is " . $diff->format('%y Years, %m month, %d days') . "</p>";
现在,我希望将差异向上舍入,例如,如果差异计算为:
40年,0个月,01天
我希望这被视为'41年'。一年之上的任何事情都会使它成为一个综合。
任何解决方案?
答案 0 :(得分:2)
只检查是否有一个月或一天,如果只是添加一年:
//.....
$diff = $date1->diff($date2);
$year = (int) $diff->format('%y');
if (((int)$diff->format('%m')) || ((int)$diff->format('%d'))) {
$year++;
}
echo "<p> The difference is " . $year . " years </p>";
答案 1 :(得分:0)
试试这个,从不同的日期得到几天,除以365(1年),并ceil(向上分数)到分天。
$date1 = "2016-04-05";
$date2 = "2088-05-05";
$date1 = date_create($date1);
$date2 = date_create($date2);
$diff = $date1->diff($date2);
//var_dump($diff);
$years = $diff->y;
$moths = $diff->m;
$days = $diff->d;
$hour = $diff->h;
$minits = $diff->i;
$second = $diff->s;
if($moths > 0 || $days > 0 || $hour > 0 || $minits > 0 || $second > 0)
{
$years++;
}
echo "<p> The difference is " . $years . " years </p>";
<强> DEMO 强>