Categories
JavaScript Answers

How to convert milliseconds to minutes and seconds with JavaScript?

Spread the love

Sometimes, we want to convert milliseconds to minutes and seconds with JavaScript.

In this article, we’ll look at how to convert milliseconds to minutes and seconds with JavaScript.

How to convert milliseconds to minutes and seconds with JavaScript?

To convert milliseconds to minutes and seconds with JavaScript, we can use some date methods.

For instance, we write

const d = new Date(Date.UTC(0, 0, 0, 0, 0, 0, 298999));

const parts = [d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds()];
const formatted = parts.map((s) => String(s).padStart(2, "0")).join(":");

to create a UTC date with the Date.UTC method and the Date constructor.

Then we put the hours, minutes, and seconds of the d date into the parts array.

getUTCHours gets the hours in UTC.

getUTCMinutes gets the minutes in UTC.

getUTCSeconds gets the seconds in UTC.

Then we prepend a 0 to each number if it has less than 2 digits with padStart after converting them to strings with String.

And we join the strings together with join.

Conclusion

To convert milliseconds to minutes and seconds with JavaScript, we can use some date methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *