Javascript 如何将毫秒转换为可读的日期 Minutes:Seconds 格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13601737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert milliseconds into a readable date Minutes:Seconds Format?
提问by GibboK
In JavaScript I have a variable Time in milliseconds.
在 JavaScript 中,我有一个以毫秒为单位的变量 Time。
I would like to know if there is any build-in function to convert efficientlythis value to Minutes:Secondsformat.
我想知道是否有任何内置函数可以有效地将此值转换为Minutes:Seconds格式。
If not could you please point me out a utility function.
如果没有,请您指出一个实用程序功能。
Example:
例子:
FROM
从
462000 milliseconds
TO
到
7:42
回答by Gerrit Bertier
Just create a Dateobject and pass the milliseconds as a parameter.
只需创建一个Date对象并将毫秒作为参数传递即可。
var date = new Date(milliseconds);
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
alert(((h * 60) + m) + ":" + s);
回答by GibboK
Thanks guys for your support, at th end I came up with this solution. I hope it can helps others.
感谢大家的支持,最后我想出了这个解决方案。我希望它可以帮助其他人。
Use:
用:
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
};
}
回答by August Karlstrom
It's easy to make the conversion oneself:
自己进行转换很容易:
var t = 462000
parseInt(t / 1000 / 60) + ":" + (t / 1000 % 60)
回答by Daniel
In case you already using Moment.jsin your project, you can use the moment.durationfunction
如果您已经在项目中使用Moment.js,则可以使用moment.duration函数
You can use it like this
你可以像这样使用它
var mm = moment.duration(37250000);
console.log(mm.hours() + ':' + mm.minutes() + ':' + mm.seconds());
output: 10:20:50
输出:10: 20: 50
See jsbinsample
参见jsbin示例
回答by Mohamed Allal
You may like pretty-msnpm package: https://www.npmjs.com/package/pretty-ms
If that what you are searching. Headless nice formatting (time in the units that are needed as ms grow), personalisable, and cover different situations. Small and efficient for what it cover.
您可能喜欢漂亮的 msnpm 包:https://www.npmjs.com/package/pretty-ms
如果这是您正在搜索的内容。无头的漂亮格式(以毫秒为单位所需的时间),可个性化,并涵盖不同的情况。它涵盖的内容小巧而高效。
回答by kmkaplan
function msToMS(ms) {
var M = Math.floor(ms / 60000);
ms -= M * 60000;
var S = ms / 1000;
return M + ":" + S;
}

