Home  >  Article  >  Backend Development  >  How to Add Two Time Intervals in PHP?

How to Add Two Time Intervals in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 02:51:02200browse

How to Add Two Time Intervals in PHP?

Add two time intervals in PHP

In PHP, you want to calculate the total duration of two time intervals and sum them in hours For minute format display, these two intervals need to be added. However, PHP's DateInterval class does not have overloaded operators, so they cannot be added directly.

To achieve this, you need to create a new DateTime object, add two intervals using the add() function, and then display the time difference from the reference point:

<code class="php">$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>

Full code example :

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

Another method is to extend the DateInterval class and customize the add() function to calculate the total time yourself:

<code class="php">class MyDateInterval extends DateInterval
{
    //...
}

$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 = MyDateInterval::fromDateInterval($interval1);
$e->add($interval2);
echo "Total interval: ", $e->format("%H:%I"), "\n";</code>

This is just to implement custom time through a custom class A method of spacing.

The above is the detailed content of How to Add Two Time Intervals in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn