phpdatetimedurationsubtraction

PHP time subtraction from 2 variables


I am trying to subtracting two variables in PHP (time format, "H:i:s"), i.ex:

$entryscan = '07:15:00';
$exitscan = '16:35:00';

How do I get the work duration? I mean $workduration = $exitscan - $entryscan; so, the answer is $workduration = '09:20:00';


Solution

  • Use php timediff function.

    $datetime1 = new DateTime($entryscan);
    $datetime2 = new DateTime($exitscan);
    $interval = $datetime1->diff($datetime2);
    echo $interval->format('%H hours');
    

    %H will give you the difference in hours.

    %I will give you the difference in minutes.

    %S will give you the difference in seconds.