如何在php中创建date-> diff时包含startdate

时间:2018-05-03 17:02:09

标签: php date datediff

如何包含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)

2 个答案:

答案 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);
?>

2:

<?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