2014-12-03 113 views
0

我在下面有這個功能。Php將秒轉換爲只讀值的可讀格式

function secondsToTime($seconds) { 
    $dtF = new DateTime("@0"); 
    $dtT = new DateTime("@$seconds"); 
    return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds'); 
} 

以上下面

0 days, 0 hours, 2 minutes and 52 seconds 

功能例如172秒回報,但我希望它是隻

2 minutes and 52 seconds 

,或者如果其小於60秒其應該忽略分鐘..

+0

如何返回包括天,如果沒有天在函數中? – Rizier123 2014-12-03 06:32:14

+0

對不起,看到我更新的功能 – 2014-12-03 06:38:23

回答

2
$seconds=172; 
function sec_to_time($seconds) { 
$hours = floor($seconds/3600); 
$minutes = floor($seconds % 3600/60); 
$seconds = $seconds % 60; 
if($hours>0) 
{ 
    return sprintf(" %d hours %02d , minutes %02d , seconds", $hours, $minutes, $seconds); 
} 
else if($minutes>0) 
{ 
    return sprintf("%02d minutes , %02d seconds", $minutes, $seconds); 
} 
else 
{ 
    return sprintf("%02d seconds", $seconds); 
} 
} 
echo sec_to_time($seconds); 

或新的答案,因爲你更新功能

function secondsToTime($seconds) { 
    $dtF = new DateTime("@0"); 
    $dtT = new DateTime("@$seconds"); 
    $a=$dtF->diff($dtT)->format('%a'); 
    $h=$dtF->diff($dtT)->format('%h'); 
    $i=$dtF->diff($dtT)->format('%i'); 
    $s=$dtF->diff($dtT)->format('%s'); 
    if($a>0) 
    { 
     return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds'); 
    } 
    else if($h>0) 
    { 
     return $dtF->diff($dtT)->format('%h hours, %i minutes and %s seconds'); 
    } 
    else if($i>0) 
    { 
     return $dtF->diff($dtT)->format(' %i minutes and %s seconds'); 
    } 
    else 
    { 
     return $dtF->diff($dtT)->format('%s seconds'); 
    } 
} 
echo secondsToTime(172); 
+0

這只是返回2:52?我需要2分52秒 – 2014-12-03 06:35:22

+0

編輯我的答案檢查它 – 2014-12-03 06:36:28

+0

完美+1 ...將接受 – 2014-12-03 06:40:35

相關問題