Antony
Antony

Reputation: 4340

Why is DateDiff producing different results to DateInterval

I am probably missing something obvious, but why is the output of the below hugely different??

function dateDiff($start,$end = null,$format = 'Y-m-d'){

    $start = '2021-12-01 12:00:00';
    $end = '2022-05-11 12:00:00';

    echo $start.'--'.$end.'<br>';

    $origin = new DateTime($start);
    $target = new DateTime($end ?? $start);

    $interval = $origin->diff($target)->d;

    $out = array(
        'diff'  => $interval,
        'dates' => array(),
    );

    $interval = DateInterval::createFromDateString('1 day');
    $period = new DatePeriod($origin,$interval,$target);

    foreach ($period as $dt) {
        $out['dates'][] = $dt->format($format);
    }

    $out['dates'][] = $end;

    print'<pre>';print_r($out);print'</pre>';
    exit;

return $out;
}

I would expect the diff figure to be the same as the number of values in the dates array. As it is, for some reason the diff() function is returning 10 days??

Upvotes: 0

Views: 19

Answers (1)

Antony
Antony

Reputation: 4340

After outputting the $diff object using print_r($interval) it appers there is a "days" property (as opposed to the "d") which gives the full days as opposed to a rubbish top level difference.

$origin->diff($target)->days;

Upvotes: 1

Related Questions