2016-03-12 97 views
4

我想將某個秒數轉換爲分鐘甚至幾小時。但我不想爲每分鐘和每小時寫一個if子句......PHP:將秒轉換爲分鐘和小時

我該如何以最簡單的方式做到這一點,並且我最簡單的意思是最短。 ;)

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

的可能的複製[轉換秒到小時:分鐘:秒](HTTP://計算器。 com/questions/3172332/convert-seconds-to-hourminutesecond) –

+0

試試這個: gmdate(「H:i:s」,685); from: http://stackoverflow.com/questions/3172332/convert-seconds-to-hourminutesecond – SaidTagnit

+0

對不起,沒有找到:(@ C.Liddell – Moritz

回答

3

看看在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

+1

@Phil極好的一點,我已經更新了我的回答 – Tom

0

使用MOD

function convert_to_string_time($num_seconds) 
{ 
    $seconds = $num_seconds % 60; 
    $min = floor($num_second/60); 
    if($min == 0) 
     return "{$seconds} sec"; 
    else 
     return "{$min} min + {$seconds} sec"; 
} 
+0

第4行($ min行)不需要第一個分號;它實際上會產生錯誤 – ihateartists

+0

@ihateartists你是對的!我編輯它。謝謝 – Phil

相關問題