phpdatetimedateinterval

How can i substract time from a DateInterval object (PHP)?


I would like to add some time to a DateInterval that is so the result of a DateTime->diff method How can I do that?

Here is a simple sample of code :

$d1 = "2024-01-01 00:00";
$d2 = date('Y-m-d H:i');
$dt1 = new DateTime($d1);
$dt2 = new DateTime($d2);

$interval = $dt1->diff($dt2);

$interval->sub('PT1H');
$interval->modify('-1 hour');

Result

Call to undefined method DateInterval::sub() 
Call to undefined method DateInterval::modify() 

Is this possible that there is no existing method to modify a DateInterval? So what is the good practice?

Thank you a lot in advance :)


Solution

  • It's normal that you get the error.

    Normally, DateInterval have no such methods, to achieve what you want, you can modify the original DateTime object instead of the DateInterval, like:

    $d1 = "2024-01-01 00:00";
    $d2 = date('Y-m-d H:i');
    $dt1 = new DateTime($d1);
    $dt2 = new DateTime($d2);
    
    $interval = $dt1->diff($dt2);
    
    $dt1->sub(new DateInterval('PT1H'));
    
    $dt1->modify('-1 hour');
    
    echo $dt1->format('Y-m-d H:i');