user2135867
user2135867

Reputation:

converting seconds to HH:MM:SS in PHP

i have tried using gmdate to convert seconds into HH:MM:SS with this code:

gmdate("H:i:s", $result["s"]

$result["s] equals 142:000

when i echo the gmdate code, it displays 00:24:02 which is wrong, it should be 00:02:36

Upvotes: 13

Views: 18752

Answers (4)

Wolf359
Wolf359

Reputation: 11

This works for me. Function format. No leading zeros and unlimited hours, days not used.

 /* WHM MOD convert a string of seconds to H:M:S format */

function sec2hms($secs) {
    $secs = round($secs);
    $secs = abs($secs);
    $hours = floor($secs / 3600) . ':';
    if ($hours == '0:') $hours = '';
    $minutes = substr('00' . floor(($secs / 60) % 60), -2) . ':';
    $seconds = substr('00' . $secs % 60, -2);
return ltrim($hours . $minutes . $seconds, '0');
}

Upvotes: 1

Glavić
Glavić

Reputation: 43552

Where is the 120 coming from? 142 (or 142.000) seconds equals 2 minutes 36 seconds (142 / 60)

142 / 60 = 2.36666667 minutes which doesn't equals 2min 36sec. 2.36666 is a decimal number, and it represents minutes. If you wish to format 2.36666 to minutes and seconds, then take the whole number as minutes, and 0.366666 * 60 as seconds, that is 22, so result is 2min 22sec.


You should cast 2nd parameter to integer, or at least remove :000 part:

$result['s'] = '142:000';
echo gmdate("H:i:s", (int)$result['s']); # 0:02:22

demo

You will have problem, if you have more than 86400 seconds (1 day). In that case you can use this.

Upvotes: 14

Nisarg
Nisarg

Reputation: 3262

Try this

echo gmdate("H:i:s", 685);

OR

days = seconds / ( 24 * 60 * 60 )
seconds -= ( days * ( 24 * 60 * 60 ) )

hours = seconds / ( 60 * 60 )
seconds -= ( hours * ( 60 * 60 ) )

minutes = seconds / 60
seconds -= ( minutes * 60 )

Upvotes: 4

Let me see
Let me see

Reputation: 5094

Y0u can try this

$getHours = floor($seconds / 3600);
$getMins = floor(($seconds - ($getHours*3600)) / 60);
$getSecs = floor($seconds % 60);
echo $getHours.':'.$getMins.':'.$getSecs;

Upvotes: 1

Related Questions