Search code examples
phpdatetimedate-difference

How calculate the sum of two DateInterval object


I have two date interval object, is there any default method to add those interval object ?

$date1 = date_create("2013-03-15");
$date2 = date_create("2013-12-12");
$diff_1=date_diff($date1,$date2);
echo $diff_1->format("%y years").' '.$diff_1->format("%m months"). ' ' . $diff_1->format("%d days");
//0 years 8 months 27 days

$date3 = date_create("2015-02-15");
$date4 = date_create("2015-12-12");
$diff_2=date_diff($date3,$date4);
echo $diff_2->format("%y years").' '.$diff_2->format("%m months"). ' ' . $diff_2->format("%d days");
//0 years 9 months 27 days

$diff_1+$diff_2 = 1 year 6 months 24 days

What i need is to calculate the sum of diff_1 and diff_2?


Solution

  • The probably easiest way is to create a new object and cloning it, adding the two (or more) DateTimeIntervals (in your case $diff_1 and $diff_2) to the new object. By now finding the difference between the new object and its clone, is the sum of the two DateTimeIntervals you originally had.

    // Define two intervals
    $date1 = date_create("2013-03-15");
    $date2 = date_create("2013-12-12");
    $diff_1 = date_diff($date1,$date2);
    
    $date3 = date_create("2015-02-15");
    $date4 = date_create("2015-12-12");
    $diff_2 = date_diff($date3,$date4);
    
    
    // Create a datetime object and clone it
    $dt = new DateTime();
    $dt_diff = clone $result;
    
    // Add the two intervals from before to the first one
    $dt->add($diff_2);
    $dt->add($diff_1);
    
    // The result of the two intervals is now the difference between the datetimeobject and its clone
    $result = $dt->diff($dt_diff);
    var_dump($result);
    

    Result of the dump includes

      ["y"]=>
        int(1)
      ["m"]=>
        int(6)
      ["d"]=>
        int(21)
    

    ..which is 1 year, 6 months and 21 days.

    Live demo

    Sidenote
    You don't have to concat so many different formats with your format(). You can do it all in a single line,

    echo $result->format("%y years %m months %d days");