"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Sum Date Intervals in PHP?

How to Sum Date Intervals in PHP?

Published on 2024-12-21
Browse:199

How to Sum Date Intervals in PHP?

Adding Date Intervals in PHP

In PHP, we may encounter situations where we need to add two or more date intervals to calculate the total duration in hours and minutes. To achieve this sum, we can follow these steps:

  1. Create DateTime objects for each time interval.
  2. Use the diff() method to calculate the difference between each pair of objects.
$a = new DateTime('14:25');
$b = new DateTime('17:30');
$interval1 = $a->diff($b);
echo "interval 1: " . $interval1->format("%H:%I");
echo "
"; $c = new DateTime('08:00'); $d = new DateTime('13:00'); $interval2 = $c->diff($d); echo "interval 2: " . $interval2->format("%H:%I"); echo "
";
  1. To obtain the total duration, we need to create a new DateTime object as a reference point.
$e = new DateTime('00:00');
  1. Clone the reference object to preserve its original time.
$f = clone $e;
  1. Add the first interval to the reference object using the add() method.
$e->add($interval1);
  1. Repeat step 5 with the second interval.
$e->add($interval2);
  1. Finally, calculate the difference between the original reference object and the modified reference object to obtain the total interval.
echo "Total interval: " . $f->diff($e)->format("%H:%I");
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3