javascriptdatetime

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().getTime()

and I have futureTime in milliseconds

var futureTime = '1432342800000'

I wanted to get difference in millisecond

var timeDiff = futureTime - currentTime

the the timeDiff was

timeDiff = '2568370873'

I want to know how many hours, minutes, seconds it is.

Could anyone help?


Solution

  • const secDiff = timeDiff / 1000; //in s
    const minDiff = timeDiff / 60 / 1000; //in minutes
    const hDiff = timeDiff / 3600 / 1000; //in hours  
    

    updated

    function msToHMS( 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