Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 541
haeminish Avatar asked Apr 23 '15 07:04

haeminish


People also ask

How do you convert milliseconds to date format?

Converting Milliseconds to Date For the current millisecond, use the function getTime() which is used in JavaScript to return the number of milliseconds from the standard date “January 1, 1970, 00:00:00 UTC” till the current date as shown below: var checkTime = new Date().

How do you convert milliseconds?

Take Input in milliseconds. Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60). Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).


2 Answers

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

like image 93
ozil Avatar answered Sep 18 '22 15:09

ozil


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

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

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

like image 31
tdbit Avatar answered Sep 21 '22 15:09

tdbit