Moritz
Moritz

Reputation: 766

PHP: convert seconds to minutes and hours

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;

Upvotes: 6

Views: 12759

Answers (2)

Phil
Phil

Reputation: 420

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";
}

Upvotes: 0

Tom
Tom

Reputation: 1223

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

Upvotes: 7

Related Questions