Categories
JavaScript Answers

How to convert milliseconds to time in JavaScript?

Spread the love

Sometimes, we want to convert milliseconds to time in JavaScript.

in this article, we’ll look at how to convert milliseconds to time in JavaScript.

How to convert milliseconds to time in JavaScript?

To convert milliseconds to time in JavaScript, we convert it to a date.

For instance, we write

const millisecondsToTime = (milli) => {
  const milliseconds = milli % 1000;
  const seconds = Math.floor((milli / 1000) % 60);
  const minutes = Math.floor((milli / (60 * 1000)) % 60);

  return minutes + ":" + seconds + "." + milliseconds;
};

to define the millisecondsToTime function.

In it, we get the milliseconds by using the % operrator.

Then we get the seconds by converting milli to seconds with (milli / 1000).

And then we use % to get the remainder when dividing that by 60.

Likewise, we get minutes by converting milli to minutes with (milli / (60 * 1000) and doing the same thing afterwards.

Finally, we concatenate the minutes, seconds, and milliseconds together.

Conclusion

To convert milliseconds to time in JavaScript, we convert it to a date.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.