2010-09-17 44 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