PHP:将秒转换为分钟和小时

6
我想将一定数量的秒转换成分钟甚至小时。但我不想为每个分钟和小时编写if语句...
有什么最简单的方法可以做到这一点?最简单的意思是最短的方式。 ;)
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;

6
可能是 Convert seconds to Hour:Minute:Second 的重复问题。 - C.Liddell
尝试一下: gmdate("H:i:s", 685); 来自: https://dev59.com/nnA75IYBdhLWcg3wqK__ - SaidTagnit
抱歉,没有找到 :( @C.Liddell - Moritz
只有在处理小数字时才使用日期。任何超过1天秒数(86400)的数字都会给出错误的输出。 - Phil
2个回答

7
看一下gmdate()函数。
$countholen = mysqli_fetch_array(mysqli_query($db, "
SELECT * FROM `blablabla` WHERE `blabla` = 'bla'
"));
$countholenfetch = $countholen["count"];

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

注意:如果你在处理大量数字,那么最好使用这种方式。
$seconds = 86401 ;
$hours = floor($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;

echo "$hours:$minutes:$seconds"; //24:0:1

1
如果您使用日期,86401将会给出“00:00:01”的结果。日期函数适用于小数字,但不适用于大数字。 - Phil

0

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

第四行($min行)不需要第一个分号;它实际上会生成一个错误。 - ihateartists
@ihateartists 你说得对!我已经编辑了。谢谢。 - Phil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接