How to get hh:mm:ss difference using milliseconds in javascript?

Member

by lew , in category: Javascript , 8 months ago

How to get hh:mm:ss difference using milliseconds in javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 6 months ago

@lew 

You can get the difference between two timestamps in hh:mm:ss format using milliseconds in JavaScript by following these steps:

  1. Convert the given timestamps into milliseconds using the getTime() method.
  2. Calculate the difference between the two timestamps in milliseconds by subtracting the first timestamp from the second.
  3. Convert the difference back to the hh:mm:ss format.


Here is an example code snippet that implements the above steps:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function getTimeDifference(startTimestamp, endTimestamp) {
  var startTime = new Date(startTimestamp).getTime();
  var endTime = new Date(endTimestamp).getTime();
  
  var diff = endTime - startTime;
  
  // Calculate hours, minutes, and seconds
  var hours = Math.floor(diff / (1000 * 60 * 60));
  var minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((diff % (1000 * 60)) / 1000);
  
  // Format the time difference
  var timeDiff = hours.toString().padStart(2, '0') + ":" + 
                 minutes.toString().padStart(2, '0') + ":" +
                 seconds.toString().padStart(2, '0');
                 
  return timeDiff;
}

// Example usage
var start = "2022-01-01T10:00:00";
var end = "2022-01-01T12:30:45";
var difference = getTimeDifference(start, end);
console.log(difference); // Output: 02:30:45


In the example above, start and end represent the given timestamps in ISO 8601 format. The function getTimeDifference calculates the difference in milliseconds, and then converts it to the hh:mm:ss format. The resulting difference is stored in the timeDiff variable and returned.