2012-11-28 79 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。 –