Convert milliseconds to hours, min, sec format in JavaScript

Convert millisecond to Minutes

Lets say we have time in milliseconds and want to generate a string in the format hours:minutes:seconds . We can use below mentioned function to achieve desired result.

getHourFormatFromMilliSeconds(millisec) {
    var seconds = (millisec / 1000).toFixed(0);
    var minutes = Math.floor(Number(seconds) / 60).toString();
    let hours;
    if (Number(minutes) > 59) {
      hours = Math.floor(Number(minutes) / 60);
      hours = (hours >= 10) ? hours : "0" + hours;
      minutes = (Number(minutes) - (hours * 60)).toString();
      minutes = (Number(minutes) >= 10) ? minutes : "0" + minutes;
    }

    seconds = Math.floor(Number(seconds) % 60).toString();
    seconds = (Number(seconds) >= 10) ? seconds : "0" + seconds;
    if (!hours) {
      hours = "00";
    }
    if (!minutes) {
      minutes = "00";
    }
    if (!seconds) {
      seconds = "00";
    }
    
      return hours + ":" + minutes + ":" + seconds;
   
  }

If we pass 3345345 to test this function it returns string in format hours : minutes and seconds format : 00:55:45

If we pass 4563355 to test this function it returns string in format hours : minutes and seconds format : 01:16:03

If we pass 34355 to test this function it returns string in format hours : minutes and seconds format : 00:0:34

Lets say we have a string returned by function as 01:16:03 , we can further break and split this into an array using delimiter (“:”). This will further help us to display string as

01 Hours 16 Minutes 03 Seconds

Happy coding 🙂

Convert milliseconds to hours, min, sec format in JavaScript

Leave a Reply

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

Scroll to top