2011-05-26 30 views
2

我期待把165秒到2:40不爲0:2:45最有效的/短的方式,採取X秒,並把它變成H:M:S

功能必須能夠適應秒值的大小。

我知道有無數的方法來做到這一點,但我正在尋找一種乾淨的方式來做到這一點,沒有任何外部庫,而不是jQuery。

+1

如果你不想使用外部庫,爲什麼那麼使用'jquery'標籤? – KooiInc 2011-05-26 06:40:09

+0

哦,jQuery恰好在頁面上,所以我可以使用jQuery。我忘了它是一個外部圖書館haha – tim 2011-05-26 07:06:56

回答

4

喜歡的東西:[Math.floor(165/60),165%60].join(':')應該工作。其實,這是2:45;〜)

[編輯]基於您的評論的功能,以秒轉換成(補零小時修剪)小時: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 
+0

先生,你的方法返回「64:10」爲3850秒,我正在尋找返回值1:04:10。感謝您收到錯字! – tim 2011-05-26 07:06:08

+0

正是我想要的,謝謝。 – tim 2011-05-26 08:46:40

0

檢查這個答案:Convert seconds to HH-MM-SS with JavaScript?

hours = totalSeconds/3600; 
totalSeconds %= 3600; 
minutes = totalSeconds/60; 
seconds = totalSeconds % 60; 
+0

我看過那裏,但選擇的答案那裏使用外部庫。 – tim 2011-05-26 06:47:52

0

嘗試是這樣的(我已經包括填充,以數字格式以每兩個字符):

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(':'); 
相關問題