Convert seconds to Hour:Minute:Second

2018-12-31 10:00发布

I need to convert seconds to "Hour:Minute:Second".

For example: "685" converted to "00:11:25"

How can I achieve this?

标签: php time
23条回答
无色无味的生活
2楼-- · 2018-12-31 10:44

Well I needed something that would reduce seconds into hours minutes and seconds, but would exceed 24 hours, and not reduce further down into days.

Here is a simple function that works. You can probably improve it... But here it is:

function formatSeconds($seconds)
{
    $hours = 0;$minutes = 0;
    while($seconds >= 60){$seconds -= 60;$minutes++;}
    while($minutes >= 60){$minutes -=60;$hours++;}
    $hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
    $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
    $seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);
    return $hours.":".$minutes.":".$seconds;
}
查看更多
爱死公子算了
3楼-- · 2018-12-31 10:44

Anyone whose looking for this in the future, this gives the format the initial poster asked for.

$init = 685;
$hours = floor($init / 3600);
$hrlength=strlen($hours);
if ($hrlength==1) {$hrs="0".$hours;}
else {$hrs=$hours;} 

$minutes = floor(($init / 60) % 60);
$minlength=strlen($minutes);
if ($minlength==1) {$mins="0".$minutes;}
else {$mins=$minutes;} 

$seconds = $init % 60;
$seclength=strlen($seconds);
if ($seclength==1) {$secs="0".$seconds;}
else {$secs=$seconds;} 

echo "$hrs:$mins:$secs";
查看更多
梦寄多情
4楼-- · 2018-12-31 10:45

What about

print date('H:i:s', mktime(0, 0, 685, 0, 0));

without any extensions

查看更多
闭嘴吧你
5楼-- · 2018-12-31 10:46

This function my be useful, you could extend it:

function formatSeconds($seconds) {

if(!is_integer($seconds)) {
    return FALSE;
}

$fmt = "";

$days = floor($seconds / 86400);
if($days) {
    $fmt .= $days."D ";
    $seconds %= 86400;
}

$hours = floor($seconds / 3600);
if($hours) {
    $fmt .= str_pad($hours, 2, '0', STR_PAD_LEFT).":";
    $seconds %= 3600;
}

$mins = floor($seconds / 60 );
if($mins) {
    $fmt .= str_pad($mins, 2, '0', STR_PAD_LEFT).":";
    $seconds %= 60;
}

$fmt .= str_pad($seconds, 2, '0', STR_PAD_LEFT);

return $fmt;}
查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 10:48

Try this:

date("H:i:s",-57600 + 685);

Taken from
http://bytes.com/topic/php/answers/3917-seconds-converted-hh-mm-ss

查看更多
登录 后发表回答