Sir I have these codes

$start_time=$row['start'];      //2017-02-09 15:04:09.000
$stop_time=date('Y-m-d H:i:s');     //2017-02-09 16:24:22.000

$duration=$start-$starttime;        // it says 2016

but i need result like this //0001:20:13

I mean I need hours in 4 digits minutes in 2 digits and second 2 digits

Please help

6 Months
Discussion Span
Last Post by diafol

You can not subtract two strings representing dates on line 4 and expect to get a difference. Besides the variables on line 4 have not been declared anywhere (but I guess you just misstyped them).

The best thing to do is to use the DateTime and the DateInterval PHP classes. There is a nice example at the later link which I adapted for your case:

$start_time = $row['start'];

$datetime1 = new DateTime($start_time);
$datetime2 = new DateTime('now');
$interval = $datetime1->diff($datetime2);
$duration = $interval->format("%H hours %I minutes %S seconds");

I am assuming that $row['start']contains a valid date string (you should add code to check this) and you are comparing it with the current time (you can addapt the code for other cases). If you want to have hours in 4 digits, use the str_pad function.

Edited by broj1: Making an ugly post look beautiful :-)


Unfortunately %H will only supply the "remainder" of hours after days taken off. Possibly:

function makeMyTime($start, $end){

    $dstart = new DateTime($start);
    $dend = new DateTime($end);

    $dayHours = $dstart->diff($dend)->format('%a') * 24;
    $hours = $dstart->diff($dend)->format('%h') + $dayHours;
    $diff = str_pad($hours, 4, '0', STR_PAD_LEFT) . $dstart->diff($dend)->format(':%I:%S');

    return $diff;


$myStart = '2017-02-10 19:00:00';
$myEnd = '2017-02-19 22:20:00';

echo makeMyTime($myStart, $myEnd);

Seems a little long-winded though.

Edited by diafol

Votes + Comments
Did not test enough :-)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.