How to Add Two Time Intervals in PHP?

Mary-Kate Olsen
Release: 2024-11-04 02:51:02
Original
198 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!