Reputation: 73918
In JavaScript I have a variable Time in milliseconds.
I would like to know if there is any build-in function to convert efficiently this value to Minutes:Seconds
format.
If not could you please point me out a utility function.
Example:
FROM
462000 milliseconds
TO
7:42
Upvotes: 5
Views: 28152
Reputation: 20870
You may like pretty-ms npm 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.
Upvotes: 1
Reputation: 37061
In case you already using Moment.js in your project, you can use the moment.duration function
You can use it like this
var mm = moment.duration(37250000);
console.log(mm.hours() + ':' + mm.minutes() + ':' + mm.seconds());
output: 10:20:50
See jsbin sample
Upvotes: 3
Reputation: 73918
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
};
}
Upvotes: 6
Reputation: 4221
Just create a Date
object and pass the milliseconds as a parameter.
var date = new Date(milliseconds);
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
alert(((h * 60) + m) + ":" + s);
Upvotes: 13
Reputation: 11377
It's easy to make the conversion oneself:
var t = 462000
parseInt(t / 1000 / 60) + ":" + (t / 1000 % 60)
Upvotes: 2
Reputation: 18960
function msToMS(ms) {
var M = Math.floor(ms / 60000);
ms -= M * 60000;
var S = ms / 1000;
return M + ":" + S;
}
Upvotes: 0