Skip to content Skip to sidebar Skip to footer

How Can I Convert Milliseconds To "hhmmss" Format Using Javascript?

I am using javascript Date object trying to convert millisecond to how many hour, minute and second it is. I have the currentTime in milliseconds var currentTime = new Date().getTi

Solution 1:

const secDiff = timeDiff / 1000; //in sconst minDiff = timeDiff / 60 / 1000; //in minutesconst hDiff = timeDiff / 3600 / 1000; //in hours  

updated

functionmsToHMS( ms ) {
    // 1- Convert to seconds:let seconds = ms / 1000;
    // 2- Extract hours:const hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
    seconds = seconds % 3600; // seconds remaining after extracting hours// 3- Extract minutes:const minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute// 4- Keep only seconds not extracted to minutes:
    seconds = seconds % 60;
    alert( hours+":"+minutes+":"+seconds);
}

const timespan = 2568370873; 
msToHMS( timespan );  

Demo

Solution 2:

If you are confident that the period will always be less than a day you could use this one-liner:

newDate(timeDiff).toISOString().slice(11,19)   // HH:MM:SS

N.B. This will be wrong if timeDiff is greater than a day.

Solution 3:

Convert ms to hh:mm:ss

functionmillisecondsToHuman(ms) {
  const seconds = Math.floor((ms / 1000) % 60);
  const minutes = Math.floor((ms / 1000 / 60) % 60);
  const hours = Math.floor((ms  / 1000 / 3600 ) % 24)

  const humanized = [
    pad(hours.toString(), 2),
    pad(minutes.toString(), 2),
    pad(seconds.toString(), 2),
  ].join(':');

  return humanized;
}
=

Solution 4:

functionmsToHMS( duration ) {

     var milliseconds = parseInt((duration % 1000) / 100),
        seconds = parseInt((duration / 1000) % 60),
        minutes = parseInt((duration / (1000 * 60)) % 60),
        hours = parseInt((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 ;
}

Solution 5:

The difference in time is in milliseconds: Get time difference between two dates in seconds

to get the difference you have to use math.floor() http://www.w3schools.com/jsref/jsref_floor.asp

var secDiff = Math.floor(timeDiff / 1000); //in svar minDiff = Math.floor(timeDiff / 60 / 1000); //in minutesvar hDiff = Math.floor(timeDiff / 3600 / 1000); //in hours

Post a Comment for "How Can I Convert Milliseconds To "hhmmss" Format Using Javascript?"