2011-01-27 123 views
1

我在php中有以下功能,如何將它轉換爲javascript?javascript長度持續時間

function length_duration ($seconds) 
{ 
    $hours = $mins = $sec = NULL; 

    //for seconds 
    if($seconds > 0) 
    $sec = ($seconds % 60 < 10) ? "0".($seconds%60) : ($seconds%60); 

    //for mins 
    if($seconds > 60) 
    $mins = (($seconds/60%60)<10) ? "0".($seconds/60%60).":" : "".($seconds/60%60).":"; 

    //for hours 
    if($seconds/60 > 60) 
    $hours = (($seconds/60/60) < 10) ? "0".($seconds/60/60).":" : "".($seconds/60/60).":"; 

    return $hours.$mins.$sec; 
} 

回答

1

大多刪除$,替換。用+,使用var聲明變量,並使用~~處理JavaScript的處理小數

的有趣的方式

演示:http://jsfiddle.net/kR4Pz/1/

function length_duration (seconds) 
{ 
    var hours = '', mins = '', sec = ''; 

    //for seconds 
    if(seconds > 0) 
    sec = (seconds % 60 < 10) ? "0"+(seconds%60) : ""+(seconds%60); 

    //for mins 
    if(seconds >= 60) 
    mins = ~~(((seconds/60)%60)<10) ? "0"+~~((seconds/60)%60)+":" : ""+~~((seconds/60)%60)+":"; 

    //for hours 
    if(seconds/60 >= 60) 
    hours = ~~(((seconds/60)/60) < 10) ? "0"+~~((seconds/60)/60)+":" : ""+~~((seconds/60)/60)+":"; 

    return hours+mins+sec; 
} 
+0

雙重按位補碼將數字強制爲整數?真有意思。 – 2011-01-27 00:18:02

1

有舍入和之間的數字到字符串轉換有一些區別兩種語言。此外,原始版本中還有一些錯誤,例如正好一分鐘的時間格式不正確。

function length_duration (seconds) 
{ 
    var hours = "", mins = "", sec = ""; 

    //for seconds 
    if(seconds > 0) 
    sec = (seconds % 60 < 10) ? "0"+String(seconds%60) : ""+String(seconds%60); 

    seconds -= (seconds % 60); 

    //for mins 
    if(seconds >= 60) 
    mins = ((seconds/60%60)<10) ? "0"+String(seconds/60%60)+":" : ""+String(seconds/60%60)+":"; 

    seconds -= (seconds % (60*60)); 

    //for hours 
    if(seconds/60 >= 60) 
    hours = ((seconds/60/60) < 10) ? "0"+String(seconds/60/60)+":" : ""+String(seconds/60/60)+":"; 

    return hours+mins+sec; 
}