2012-11-28 80 views
5

在JavaScript中,我有一個以毫秒爲單位的可變時間。如何將毫秒轉換爲可讀日期分鐘:秒格式?

我想知道是否有任何內置函數將有效地轉換爲這個值爲Minutes:Seconds格式。

如果不是,請您指出一個實用功能。

實施例:

FROM

462000 milliseconds 

TO

7:42 
+4

不要你的意思是7:42? –

+0

我知道這不是_efficient_,但我只是'新日期(462000).toString()。匹配(/ \ d {2}:\ d {2}:\ d {2} /)[0] ' - 如果你知道它總是不到24小時。 –

+0

我以爲相同的解決方案,但我不知道它是效率;-) – GibboK

回答

5

謝謝你們的支持,在日結束時,我想出了這個解決方案。我希望它能幫助別人。

用途:

var videoDuration = convertMillisecondsToDigitalClock(18050200).clock; // CONVERT DATE TO DIGITAL FORMAT 

// CONVERT MILLISECONDS TO DIGITAL CLOCK FORMAT 
function convertMillisecondsToDigitalClock(ms) { 
    hours = Math.floor(ms/3600000), // 1 Hour = 36000 Milliseconds 
    minutes = Math.floor((ms % 3600000)/60000), // 1 Minutes = 60000 Milliseconds 
    seconds = Math.floor(((ms % 360000) % 60000)/1000) // 1 Second = 1000 Milliseconds 
     return { 
     hours : hours, 
     minutes : minutes, 
     seconds : seconds, 
     clock : hours + ":" + minutes + ":" + seconds 
    }; 
} 
9

只需創建一個對象Date並傳遞毫秒作爲參數。

var date = new Date(milliseconds); 
var h = date.getHours(); 
var m = date.getMinutes(); 
var s = date.getSeconds(); 
alert(((h * 60) + m) + ":" + s); 
+0

你的警報是錯誤的 – musefan

+0

似乎我有點快速在這一個,修復它:) –

+0

這''時間:分鐘:秒'*不* *分鐘:秒'。 – kmkaplan

0
function msToMS(ms) { 
    var M = Math.floor(ms/60000); 
    ms -= M * 60000; 
    var S = ms/1000; 
    return M + ":" + S; 
} 
2

這很容易進行轉換自己:

var t = 462000 
parseInt(t/1000/60) + ":" + (t/1000 % 60) 
2

如果你已經在你的項目中使用Moment.js,則可以使用moment.duration功能

您可以使用它像這樣

var mm = moment.duration(37250000); 
console.log(mm.hours() + ':' + mm.minutes() + ':' + mm.seconds()); 

輸出:十點20分五十秒

jsbin樣品

+0

如果提供了正確的輸入,它將輸出爲1:2:5。不是1:02:05。 –