最有效/最短的方法是花X秒并将其变成h:m:s

| 我希望将165秒变成2:40而不是0:2:45 该功能必须能够适应秒值的大小。 我知道有无数种方法可以做到这一点,但是我正在寻找一种干净的方法来做到这一点,而不需要除jQuery外的任何外部库。     
已邀请:
类似于:
[Math.floor(165/60),165%60].join(\':\')
应该起作用。其实是2:45;〜) [edit]根据您的评论,将秒转换为(零填充,修剪小时)hr:mi:se字符串的函数
function hms(sec){
 var   hr = parseInt(sec/(60*60),10)
     , mi = parseInt(sec/60,10)- (hr*60)
     , se = sec%60;
 return [hr,mi,se]
         .join(\':\')
         .replace(/\\b\\d\\b/g,
            function(a){ 
             return Number(a)===0 ? \'00\' : a<10? \'0\'+a : a; 
            }
          )
         .replace(/^00:/,\'\');
}
alert(hms(165)); //=> 02:45
alert(hms(3850)); //=> 01:04:10
    
检查这个答案:使用JavaScript将秒转换为HH-MM-SS?
hours = totalSeconds / 3600;
totalSeconds %= 3600;
minutes = totalSeconds / 60;
seconds = totalSeconds % 60;
    
尝试这样的操作(我已包含填充以将数字分别设置为两个字符):
String.prototype.padLeft = function(n, pad)
{
    t = \'\';
    if (n > this.length){
        for (i = 0; i < n - this.length; i++) {
            t += pad;
        }
    }
    return t + this;
}

var seconds = 3850;
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor(seconds % 3600 / 60);

var time = [hours.toString().padLeft(2, \'0\'), 
            minutes.toString().padLeft(2, \'0\'), 
            (seconds % 60).toString().padLeft(2, \'0\')].join(\':\');
    

要回复问题请先登录注册