javascript length duration
i have following function in php, how can i convert this in 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开发者_如何学C/60).":" : "".($seconds/60/60).":";
return $hours.$mins.$sec;
}
mostly remove the $, replace . with +, declare variables with var and use ~~ to deal with the funny way javascript handles decimals
demo: 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;
}
There are a few differences in rounding and number-to-string conversion between the two languages. Also, there are a couple of bugs in the original, where for example a time of exactly one minute would format incorrectly.
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;
}
精彩评论