Convert milliseconds to minutes and seconds
Question:
How to convert milliseconds to minutes and seconds? Answer:
function convertMsToTime(ms) {
const totalSeconds = Math.round(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds - hours * 3600) / 60);
const seconds = totalSeconds - hours * 3600 - minutes * 60;
return `${hours}:${minutes}:${seconds}`;
}
Description:
To convert milliseconds to hours, minutes, and seconds you need to execute some mathematical calculations.
- Convert the milliseconds value to seconds by dividing it by 1000 and converting it to an integer using the
Math.round()
method. - Then calculate how many whole hours the resulting seconds add up to. Here you have to use the
Math.floor()
method. - Then see how many whole minutes the remaining seconds add up to.
- Finally, subtracting the seconds in whole hours and whole minutes from the original
totalSeconds
value gives the remaining seconds.
Reference:
Math floor reference
Share "How to convert milliseconds to minutes and seconds?"
Related snippets:
- Convert milliseconds to minutes and seconds
- Check if date is valid in JavaScript
- Generate random date with JavaScript
- Generate random date in a range with JavaScript
- Check if date is today
- Get month name from Date in JavaScript
- Get the current date in JavaScript
- Get difference between 2 dates in JavaScript
- Get yesterday's date in JavaScript
- Get tomorrow's date in JavaScript
Tags:
convert, millisecond, hour, minute, second, javascript Technical term:
Convert milliseconds to minutes and seconds