. Advertisement .
..3..
. Advertisement .
..4..
Have trouble converting milliseconds to hours or minutes in the JavaScript programming language? This guide will show you how to complete this task; it is easier than you think.
Method Of Converting Milliseconds To Hours Or Minutes
You can use the function convertMsToTime to perform this task. Here is an example of milliseconds to hours conversion.
function msToTime(duration) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
console.log(msToTime(300000))
If the numbers for the minutes or hours hold a single-digit value that is less than 10, this function will take care of inserting one leading zero.
Keep in mind to check the outcome to avoid having the result fluctuate between values of double and single digits based on the minute and hour.
Below is what we accomplished in the function convertMsToTime.
- Divided the millisecond figure by 1000 to convert it to seconds.
- Divided the second figure by 60 to convert it to minutes.
- Divided the minute figure by 60 to convert it to hours.
- Utilized the modulo operator % to reset to 0 when, for instance, the user entered 86400000 milliseconds, which equates to 24 hours.
Here, we utilize the method Math.floor() to round a number value down to the closest integer. For example:
Math.floor(45.95); // 45
Math.floor(45.05); // 45
Math.floor(4); // 4
Math.floor(-45.05); // -46
Math.floor(-45.95); // -46
The modulus operator % was also utilized to obtain the remainder of the division.
Keep in mind the modulus operator is frequently used in clock time hh:mm:ss to distinguish between the hour, minute, and second value. Using the same methodology, the millisecond values can also be converted to years, months, weeks, days, etc.
The function convertMsToTime will also roll the hour values over by default if they are more than 24. For instance, when the millisecond values equal 36 hours, the line hours = hours % 24 will set the hour values to 12.
Still, you may not need to roll the hour values over. In this case, comment out the line hours = hours % 24 to prevent the hours from rolling over.
The Bottom Line
There you have the complete guide on converting milliseconds to hours or minutes in the JavaScript programming language. As you can see, the process is fairly simple; you just need to follow the steps above. Hopefully, you will find this post helpful and easy to understand.We also provide a tutorial on converting seconds to hh:mm:ss, so check it out if you need to perform this task in JavaScript.
Leave a comment