from milliseconds to hours in js 1

from milliseconds to hours in js

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))

Here is what the above code is Doing:
1. We're using the parseInt() function to convert the milliseconds into an integer.
2. We're using the Math.floor() function to round the number down to the nearest whole number.
3. We're using the modulus operator (%) to get the remainder of the division.
4. We're using the Math.floor() function to round the number down to the nearest whole number.
5. We're using the Math.floor() function to round the number down to the nearest whole number.
6. We're using the Math.floor() function to round the number down to the nearest whole number.
7. We're using the ternary operator to check if the hours are less than 10. If they are, we're adding a 0 in front of the number.
8. We're using the ternary operator to check if the minutes are less than 10. If they are, we're adding a 0 in front of the number.
9. We're using the ternary operator to check if the seconds are less than 10. If they are, we're adding a 0 in front of the number.
10. We're returning the hours, minutes, seconds, and milliseconds.

Similar Posts