How to add two date ranges in PHP
Adding two date ranges to calculate the total hour and minute duration is a problem for many Questions for PHP programmers. Let's try to understand how to do this.
Problem Description
The user wants to add two date intervals in the following way to get the total duration in hour and minute format:
<code class="php">$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);</code>
Question Answers
PHP does not have operator overloading, so when adding objects with objects, PHP will first try to convert them to strings, but DateInterval does not support this operation.
To solve this problem, we need to use another method:
Code Example
Here is a code example using the above method:
<code class="php">$a = new DateTime('14:25'); $b = new DateTime('17:30'); $interval1 = $a->diff($b); echo "interval 1: " . $interval1->format("%H:%I") . "\n"; $c = new DateTime('08:00'); $d = new DateTime('13:00'); $interval2 = $c->diff($d); echo "interval 2: " . $interval2->format("%H:%I") . "\n"; $e = new DateTime('00:00'); $f = clone $e; $e->add($interval1); $e->add($interval2); echo "Total interval : " . $f->diff($e)->format("%H:%I") . "\n";</code>
Output:
interval 1: 03:05 interval 2: 05:00 Total interval : 08:05
Alternative approach (custom DateInterval)
If you want to go deeper, you can also consider creating your own DateInterval extension and redefining the addition operation. This is a more advanced approach that requires a deep understanding of PHP extension development.
The above is the detailed content of How to Add Two Date Intervals in PHP to Find Total Time Duration?. For more information, please follow other related articles on the PHP Chinese website!