Comparing two DateInterval PHP objects

Published on 2022-07-13 • Modified on 2022-07-13

This snippet shows how to compare two DateInterval objects. We can't directly use the spaceship operator on DateInterval objects or we would get the error: 'Warning: Cannot compare DateInterval objects'. A simple method is to add the two intervals to the current date and compare the resulting dates; this time, we can use the spaceship operator <=>.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet210Trait
{
    public function snippet210(): void
    {
        $interval1 = new \DateInterval('P1W');
        $interval2 = new \DateInterval('P2W');

        echo $this->compareDateIntervals($interval1, $interval2).PHP_EOL;
        echo $this->compareDateIntervals($interval2, $interval1).PHP_EOL;
        echo $this->compareDateIntervals($interval1, $interval1).PHP_EOL;

        // That's it! 😁
    }

    private function compareDateIntervals(\DateInterval $i1, \DateInterval $i2): int
    {
        $dateRef = new \DateTimeImmutable();

        return $dateRef->add($i1) <=> $dateRef->add($i2);
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet