javascript长度持续时间

时间:2011-01-27 00:01:53

标签: php javascript jquery

我在php中有以下功能,如何在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;
 }

2 个答案:

答案 0 :(得分: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;
 }

答案 1 :(得分: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;
}