Search code examples
phpdatedatetimeformathour

How can I add two date strings in the format HH:MM:SS together?


I am saving the variables in the format of HH:MM:SS. I want to sum up several variables such as:

TotalTime += var1+var2

It gives me the result of 0, whats the right format for getting the sum as HH:MM:SS?


Solution

  • This should work for you:

    Here I just converted the first date into a DateTime object and the second date I converted into a DateInterval object, which I then can add() to the first date.

    <?php
    
        $var1 = "12:23:01";
        $var2 = "05:22:45";
    
        $date = new DateTime($var1);
        list($hours, $minutes, $seconds) = explode(":", $var2);
        $interval = new DateInterval("PT" . $hours . "H" . $minutes . "M" . $seconds . "S");
    
        $date->add($interval);
        echo $date->format("H:i:s");
    
    ?>
    

    output:

    17:45:46