2010-09-17 54 views
89

这是一个常见问题,但我不知道如何解决它。下面的代码工作正常。JavaScript秒到分和秒

var mind = time % (60 * 60); 
var minutes = Math.floor(mind/60); 

var secd = mind % 60; 
var seconds = Math.ceil(secd); 

然而,当我到1个小时即3600单位为秒,返回0分钟以及0秒。我怎样才能避免这一点,因此它返回所有的分钟?

谢谢

+0

那是因为当时间= 3600,3600%,3600是始终为0 ...所以一切将根据你的计算为0 。 – MSI 2010-09-17 06:59:18

回答

219

你做错了。要获得完整分钟数,分总秒60(60秒/分钟)的数量:

var minutes = Math.floor(time/60); 

而要获得剩下秒,60乘以充分分钟,距离总秒数减去:

var seconds = time - minutes * 60; 

现在,如果你也想获得完整的时间也由3600分的总秒数(60分/小时·60秒/分钟),然后再计算剩余秒:

var hours = Math.floor(time/3600); 
time = time - hours * 3600; 

然后你计算完整的分钟数和剩余的秒数。

奖励:

使用下面的代码来美化打印时间(由德鲁建议)

function str_pad_left(string,pad,length) { 
    return (new Array(length+1).join(pad)+string).slice(-length); 
} 

var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2); 
+37

通过执行'var seconds = time%60'来获得剩余时间会更清洁一些。 – 2011-12-08 15:20:14

+0

如何将前导零添加到秒?结果显示为0:5。我希望它是0:05 – 2012-04-01 12:49:11

+7

@Radio使用 'function str_pad_left(string,pad,length)添加前导零{ return(new Array(length + 1).join(pad)+ string).slice(-length );} var finalTime = str_pad_left(minutes,'0',2)+':'+ str_pad_left(seconds,'0',2);' – Dru 2012-12-06 07:20:50

0

你已经做了足够的代码来跟踪分钟和秒的时间部分。

你可以做的是在增加的时间因素:

var hrd = time % (60 * 60 * 60); 
var hours = Math.floor(hrd/60); 

var mind = hrd % 60; 
var minutes = Math.floor(mind/60); 

var secd = mind % 60; 
var seconds = Math.ceil(secd); 

var moreminutes = minutes + hours * 60 

这会给你你需要的东西也。

+0

我试着用“时间”秒作为它并没有工作。例如,975秒意味着hrd = 975,这意味着小时数为16. – Spedge 2013-09-11 10:28:41

17

您还可以使用原生的Date对象:

var date = new Date(null); 
date.setSeconds(timeInSeconds); 

// retrieve time ignoring the browser timezone - returns hh:mm:ss 
var utc = date.toUTCString(); 
// negative start index in substr does not work in IE 8 and earlier 
var time = utc.substr(utc.indexOf(':') - 2, 8) 

// retrieve each value individually - returns h:m:s 
var time = date.getUTCHours() + ':' + date.getUTCMinutes() + ':' + date.getUTCSeconds(); 

// does not work in IE8 and below - returns hh:mm:ss 
var time = date.toISOString().substr(11, 8); 

// not recommended - only if seconds number includes timezone difference 
var time = date.toTimeString().substr(0, 8); 

当然这种解决方案仅适用于timeInSeconds不超过24小时;)

+1

没有想过让Date对象处理格式。不太灵活,但是如果你想要hh:mm:ss(或者其中的一个小部分),这很好 – MartinAnsty 2012-05-02 21:51:52

+0

我用25秒的时间试了这个,它返回了01:00:25,这相当于1小时25秒。 – timstermatic 2013-08-19 12:32:34

+0

是的,可能是因为你的时区。我已经更新了解决方案来处理这种情况。 – hamczu 2013-08-21 11:45:48

57

另一种奇特的解决方案:

function fancyTimeFormat(time) 
{ 
    // Hours, minutes and seconds 
    var hrs = ~~(time/3600); 
    var mins = ~~((time % 3600)/60); 
    var secs = time % 60; 

    // Output like "1:01" or "4:03:59" or "123:03:59" 
    var ret = ""; 

    if (hrs > 0) { 
     ret += "" + hrs + ":" + (mins < 10 ? "0" : ""); 
    } 

    ret += "" + mins + ":" + (secs < 10 ? "0" : ""); 
    ret += "" + secs; 
    return ret; 
} 
+1

这个解决方案也适用于'time'的负值 – Pylinux 2013-10-20 18:06:43

+7

'~~'的含义是什么? – 2014-12-29 19:03:36

+5

这是'Math.floor'的基本手势,请参阅[此链接](http://rocha.la/JavaScript-bitwise-operators-in-practice)。 – lapin 2015-05-20 11:10:35

0

我思考一个更快的方式来完成这件事,这就是我想出的

var sec = parseInt(time); 
var min=0; 
while(sec>59){ sec-=60; min++;} 

如果我们要转换的 “时间”,以分和秒,例如:

// time = 75,3 sec 
var sec = parseInt(time); //sec = 75 
var min=0; 
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1 
2

秒到h:mm:ss的

var hours = Math.floor(time/3600); 
time -= hours * 3600; 

var minutes = Math.floor(time/60); 
time -= minutes * 60; 

var seconds = parseInt(time % 60, 10); 

console.log(hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds)); 
1

对于零添加我真的不看需要有一个完整的其它功能,你可以简单地使用例如

var mins=Math.floor(StrTime/60); 
var secs=StrTime-mins * 60; 
var hrs=Math.floor(StrTime/3600); 
RoundTime.innerHTML=(hrs>9?hrs:"0"+hrs) + ":" + (mins>9?mins:"0"+mins) + ":" + (secs>9?secs:"0"+secs); 

它为什么我们在首位的条件语句。

(条件?如果为真:如果为false)因此如果秒数大于9而不是只显示秒数否则在其之前添加一个字符串0。

8

要添加前导零,我只想做:

var minutes = "0" + Math.floor(time/60); 
var seconds = "0" + (time - minutes * 60); 
return minutes.substr(-2) + ":" + seconds.substr(-2); 

尼斯和短

0

我建议另一种解决方案:

function formatTime(nbSeconds, hasHours) { 
 
    var time = [], 
 
     s = 1; 
 
    var calc = nbSeconds; 
 

 
    if (hasHours) { 
 
     s = 3600; 
 
     calc = calc/s; 
 
     time.push(format(Math.floor(calc)));//hour 
 
    } 
 

 
    calc = ((calc - (time[time.length-1] || 0)) * s)/60; 
 
    time.push(format(Math.floor(calc)));//minute 
 

 
    calc = (calc - (time[time.length-1])) * 60; 
 
    time.push(format(Math.round(calc)));//second 
 

 

 
    function format(n) {//it makes "0X"/"00"/"XX" 
 
     return (("" + n)/10).toFixed(1).replace(".", ""); 
 
    } 
 

 
    //if (!hasHours) time.shift();//you can set only "min: sec" 
 

 
    return time.join(":"); 
 
}; 
 
console.log(formatTime(3500));//58:20 
 
console.log(formatTime(305));//05:05 
 
console.log(formatTime(75609, true));//21:00:09 
 
console.log(formatTime(0, true));//00:00:00

32

适用人群下降中希望快速简单,因此很短olution到格式秒进M:SS

function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s} 

完成..
该函数接受一个Number(优选)一个String(2转化 '处罚',这可以通过在前面加上该减半+函数调用的参数s,如:fmtMSS(+strSeconds)),表示正整数秒s作为参数。

例子:

fmtMSS( 0); // 0:00 
fmtMSS( '8'); // 0:08 
fmtMSS( 9); // 0:09 
fmtMSS( '10'); // 0:10 
fmtMSS( 59); // 0:59 
fmtMSS(+'60'); // 1:00 
fmtMSS( 69); // 1:09 
fmtMSS(3599); // 59:59 
fmtMSS('3600'); // 60:00 
fmtMSS('3661'); // 61:01 
fmtMSS(7425); // 123:45 

击穿:

function fmtMSS(s){ // accepts seconds as Number or String. Returns m:ss 
    return(s -   // take value s and subtract (will try to convert String to Number) 
      (s %= 60) // the new value of s, now holding the remainder of s divided by 60 
         // (will also try to convert String to Number) 
     )/60 + ( // and divide the resulting Number by 60 
         // (can never result in a fractional value = no need for rounding) 
         // to which we concatenate a String (converts the Number to String) 
         // who's reference is chosen by the conditional operator: 
      9 < s  // if seconds is larger than 9 
      ? ':'  // then we don't need to prepend a zero 
      : ':0'  // else we do need to prepend a zero 
     ) + s ;  // and we add Number s to the string (converting it to String as well) 
} 

注:负范围可以通过预先(0>s?(s=-s,'-'):'')+到返回式加入(实际上,(0>s?(s=-s,'-'):0)+会工作为好)。

0

我知道它已经在很多方面解决了。我需要这个函数来处理After Effects脚本,其中速度或命名空间污染不是问题。我把它放在这里是为了某个需要类似东西的人。我也写了一些测试,工作得很好。因此,这里的代码:

Number.prototype.asTime = function() { 
    var hour = Math.floor(this/3600), 
     min = Math.floor((this - hour * 3600)/60), 
     sec = this - hour * 3600 - min * 60, 
     hourStr, minStr, secStr; 
    if(hour){ 
     hourStr = hour.toString(), 
     minStr = min < 9 ? "0" + min.toString() : min.toString(); 
     secStr = sec < 9 ? "0" + sec.toString() : sec.toString(); 
     return hourStr + ":" + minStr + ":" + secStr + "hrs"; 
    } 
    if(min){ 
     minStr = min.toString(); 
     secStr = sec < 9 ? "0" + sec.toString() : sec.toString(); 
     return minStr + ":" + secStr + "min"; 
    } 
    return sec.toString() + "sec"; 
} 
3

一个一个衬垫(带小时不工作):

function sectostr(time) { 
    return ~~(time/60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60; 
} 
0

把我的两分钱中:

function convertSecondsToMinutesAndSeconds(seconds){ 
      var minutes; 
      var seconds; 
      minutes = Math.floor(seconds/60); 
      seconds = seconds%60; 

      return [minutes, seconds]; 
     } 

所以这样的:

var minutesAndSeconds = convertSecondsToMinutesAndSeconds(101); 

将有以下输出:

[1,41]; 

然后你就可以像这样打印:

console.log('TIME : ' + minutesSeconds[0] + ' minutes, ' + minutesSeconds[1] + ' seconds'); 

//TIME : 1 minutes, 41 seconds 
3
function secondsToMinutes(time){ 
    return Math.floor(time/60)+':'+Math.floor(time % 60); 
} 
+2

这可以用零填充秒来改进: '''function secondsToMinutes(time){ return Math.floor(0/60)+':'+('0'+ Math.floor(0%60) ).slice(-2); }''' – Kus 2017-12-07 06:00:07

+0

不错!谢谢@ Kus。只是你可能想用'time'替换这两个'0',我正确吗? – mikey 2018-02-19 23:20:49

+1

@mikey哎呀!是,'function secondsToMinutes(time){return Math.floor(time/60)+':'+('0'+ Math.floor(time%60))。slice(-2)}' – Kus 2018-02-21 22:38:11