5

I would like to convert a certain number of seconds to minutes and even hours. But i don't want to write an if clause for every minute and hour etc. ...

How can I do that in the easiest way, and with easiest I mean shortest. ;)

PHP:

$countholen = mysqli_fetch_array(mysqli_query($db, "
SELECT * FROM `blablabla` WHERE `blabla` = 'bla'
"));
$countholenfetch = $countholen["count"];
if ($countholenfetch <= 60){
    $count = $countholenfetch . " sec";
}
if ($countholenfetch > 60){
    $countholenfetch = $countholenfetch - 60;
    $count = "1 min" . " + " . $countholenfetch . " sec";
}
//...if clause with 120, 180, 240 etc. instead of 60 till 3600 and another if clause in an if clause...
echo $count;
Moritz
  • 745
  • 1
  • 10
  • 32
  • 6
    Possible duplicate of [Convert seconds to Hour:Minute:Second](http://stackoverflow.com/questions/3172332/convert-seconds-to-hourminutesecond) – C.Liddell Mar 12 '16 at 17:27
  • Try this: gmdate("H:i:s", 685); from: http://stackoverflow.com/questions/3172332/convert-seconds-to-hourminutesecond – SaidTagnit Mar 12 '16 at 17:33
  • Sorry, didn't find that :( @C.Liddell – Moritz Mar 12 '16 at 17:38
  • Only use date if you are working with small numbers. Anything number over 1 days worth of seconds (86400) will give the wrong output. – Phil Mar 12 '16 at 17:46

2 Answers2

7

Take a look at the gmdate() function.

$countholen = mysqli_fetch_array(mysqli_query($db, "
SELECT * FROM `blablabla` WHERE `blabla` = 'bla'
"));
$countholenfetch = $countholen["count"];

echo gmdate("H:i:s", $countholenfetch);

Note: If you are working with large numbers, then use something like this instead,

$seconds = 86401 ;
$hours = floor($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;

echo "$hours:$minutes:$seconds"; //24:0:1
Tom
  • 1,223
  • 1
  • 16
  • 27
  • 1
    If you use date, 86401 is going to give the result of "00:00:01". A date function will work for small numbers, but not big numbers. – Phil Mar 12 '16 at 17:44
0

Use mod

function convert_to_string_time($num_seconds)
{
    $seconds = $num_seconds % 60;
    $min = floor( $num_seconds / 60 );
    if( $min == 0 )
        return "{$seconds} seconds";
    else
        return "{$min} minutes {$seconds} seconds";
}
Phil
  • 410
  • 3
  • 12