How to convert seconds to the "Time: Minute: Second" format?

9

How can I convert a value in seconds to a format of 'hours: minutes: seconds'.

Example: 685 converted to 00:11:25

How do I get there?

    
asked by anonymous 21.07.2015 / 23:54

3 answers

10

You can split the seconds to find the hours and minutes:

$total = 685;
$horas = floor($total / 3600);
$minutos = floor(($total - ($horas * 3600)) / 60);
$segundos = floor($total % 60);
echo $horas . ":" . $minutos . ":" . $segundos;

See running on ideone .

    
21.07.2015 / 23:59
14

You can use the gmdate() function:

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

Refer to this response of SOen

    
23.05.2017 / 14:37
1

In addition to the calculation, already passed by Maniero :

$horas = floor($total / 3600);
$minutos = floor(($total - ($horas * 3600)) / 60);
$segundos = floor($total % 60);

It's important to remember that if one of the numbers is less than 10, then a format like this might be:

1:4:31

When expected should be:

01:04:31

For this you can use str_pad or sprintf (this last suggestion for Wallace ) as I suggested in link :

<?php
function getFullHour($input) {
    $seconds = intval($input); //Converte para inteiro

    $negative = $seconds < 0; //Verifica se é um valor negativo

    if ($negative) {
        $seconds = -$seconds; //Converte o negativo para positivo para poder fazer os calculos
    }

    $hours = floor($seconds / 3600);
    $mins = floor(($seconds - ($hours * 3600)) / 60);
    $secs = floor($seconds % 60);

    $sign = $negative ? '-' : ''; //Adiciona o sinal de negativo se necessário

    return $sign . sprintf('%02d:%02d:%02d', $hours, $mins, $secs);
}

echo getFullHour(685), PHP_EOL; //00:11:25

echo getFullHour(140801), PHP_EOL; //39:06:41
echo getFullHour(100800), PHP_EOL; //28:00:00

echo getFullHour(-140801), PHP_EOL; //-39:06:41
echo getFullHour(-100800), PHP_EOL; //-28:00:00

See an example in IDEONE: link

    
09.04.2018 / 22:28