Home >Backend Development >PHP Tutorial >How to Add Two Date Intervals in PHP?

How to Add Two Date Intervals in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 06:02:301030browse

How to Add Two Date Intervals in PHP?

How to Add Two Date Intervals in PHP

PHP doesn't support operator overloading. Objects are first converted to strings when using the addition operator ( ). However, DateInterval doesn't support string conversion.

<code class="php">interval 1: 03:05
interval 2: 05:00
Total interval : 08:05</code>

Instead, create a new DateTime object, use the add() function to add the intervals, and calculate the difference to 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>

Alternate Approach

Considering the internal storage structure of DateInterval, extending it and performing the calculation manually is also possible:

<code class="php">class MyDateInterval extends DateInterval
{
    public static function fromDateInterval(DateInterval $from)
    {
        return new MyDateInterval($from->format('P%yY%dDT%hH%iM%sS'));
    }
                                  
    public function add(DateInterval $interval)
    {
        foreach (str_split('ymdhis') as $prop)
        {
            $this->$prop += $interval->$prop;
        }
    }
}

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

Note: DateInterval extensions are possible with PHP extensions.

The above is the detailed content of How to Add Two Date 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