How we can add two date intervals in PHP

Viewed 27486

i want to add two date intervals to calculate the total duration in hours and minutes in fact i want to perform addittion as shown below:

$a = new DateTime('14:25');
$b = new DateTime('17:30');
$interval1 = $a->diff($b);
echo "interval 1 : " . $interval1->format("%H:%I");
echo "<br />";

$c = new DateTime('08:00');
$d = new DateTime('13:00');
$interval2 = $c->diff($d);
echo "interval 2 : " . $interval2->format("%H:%I");
echo "<br />";

echo "Total interval : " . $interval1 + $interval2;

Any idea how to perform this type of interval addition to get the sum of the two intervals in total hours and minutes format in PHP

4 Answers

I had the same situation. I solve it for my case by creating a new stdClass, this object emulates a DateInterval object, however it is not a real DateInterval object. Then I looping over every real DateInterval while performing an compound assignment operation (for example +=) on the desired property. See below:

$dateTimeA = new DateTime('-10 day');
$dateTimeB = new DateTime('-8 day');
$dateTimeC = new DateTime('-6 day');
$dateTimeD = new DateTime('-4 day');

$intervalA = date_diff($dateTimeA, $dateTimeB);
$intervalB = date_diff($dateTimeC, $dateTimeD);

$intervalC = new StdClass; // $intervalC is an emulation of DateInterval 
$intervalC->days = 0;

foreach([$intervalA, $intervalB] as $interval) {
    $intervalC->days += (int)$interval->format('%d');
}


var_dump($intervalC);
/*
object(stdClass)[7]
  public 'days' => int 4
*/
Related