如何包含startdate。当你计算几天时它会忽略第一天,但我也希望包括第一天。
$d1 = '2018-02-01 00:00:00';
$d2 = '2018-02-05 00:00:00';
function timeDifference($dT1, $dT2){
$d1 = new DateTime($dT1);
$d2 = new DateTime($dT2);
$d = $d1->diff($d2);
$total = $d->days;
$month = $d->m.' months';
$days = $d->d.' days';
if ($total > 30) {
$returnDate = $month.' '.$days;
}
else {
$returnDate = $days;
}
return $returnDate;
}
echo timeDifference($d1, $d2); // 4 (i want 5)
答案 0 :(得分:1)
嗯,01.和05.之间的区别是四天,它不会忽略任何东西。为什么不这样做?
€dit:请注意,对于超过一个月的日期差异(例如30天+1 = 31,但该月只有30天......),这仍然可能出错。
<?PHP
$d1 = '2018-02-01 00:00:00';
$d2 = '2018-02-05 00:00:00';
function timeDifference($dT1, $dT2){
$d1 = new DateTime($dT1);
$d2 = new DateTime($dT2);
$d = $d1->diff($d2);
$total = $d->days;
$month = $d->m.' months';
$dayDifference = $d->d;
if($dayDifference !== 0)
{
$dayDifference++;
}
$days = $dayDifference.' days';
if ($total > 30) {
$returnDate = $month.' '.$days;
}
else {
$returnDate = $days;
}
return $returnDate;
}
echo timeDifference($d1, $d2);
?>
<?PHP
$d1 = '2018-02-01 00:00:00';
$d2 = '2018-02-05 00:00:00';
function timeDifference($dT1, $dT2){
$d1 = new DateTime($dT1);
$d1->sub(new DateInterval("P1D"));
$d2 = new DateTime($dT2);
$d = $d1->diff($d2);
$total = $d->days;
$month = $d->m.' months';
$days = $d->d.' days';
if ($total > 30) {
$returnDate = $month.' '.$days;
}
else {
$returnDate = $days;
}
return $returnDate;
}
echo timeDifference($d1, $d2);
?>
答案 1 :(得分:0)
该功能按预期工作。在日期2018-02-01 00:00:00
和日期2018-02-05 00:00:00
之间,有效期为4天(01,02,03,04)。
第五个不计算在内,因为2018-02-05 00:00:00
的日期被视为上限。
如果您希望函数返回5而不是4,请在其中添加增量或使右侧输入日期为2018-02-06 00:00:00
。