How to calculate time difference between lines in javascript

is that I have two hours in string format and I need to calculate the difference in javascript, for example:

a = "10:22:57"

b = "10:30:00"

difference = 00:07:03?

+4
source share
4 answers

Although using a Date or library is fine (and probably simpler), here is an example of how to do this β€œmanually” with a bit of math. The idea is this:

  • Parse the line, extract the hour, minutes and seconds.
  • Calculate the total number of seconds.
  • Subtract both numbers.
  • Format the seconds as hh:mm:ss .

Example:

 function toSeconds(time_str) { // Extract hours, minutes and seconds var parts = time_str.split(':'); // compute and return total seconds return parts[0] * 3600 + // an hour has 3600 seconds parts[1] * 60 + // a minute has 60 seconds +parts[2]; // seconds } var difference = Math.abs(toSeconds(a) - toSeconds(b)); // compute hours, minutes and seconds var result = [ // an hour has 3600 seconds so we have to compute how often 3600 fits // into the total number of seconds Math.floor(difference / 3600), // HOURS // similar for minutes, but we have to "remove" the hours first; // this is easy with the modulus operator Math.floor((difference % 3600) / 60), // MINUTES // the remainder is the number of seconds difference % 60 // SECONDS ]; // formatting (0 padding and concatenation) result = result.map(function(v) { return v < 10 ? '0' + v : v; }).join(':'); 

Demo

+13
source

Make two Date objects from them. Then you can compare.

Get the value from both dates you want to compare and do a subtraction. Similar to this (suppose foo and bar are dates):

 var totalMilliseconds = foo - bar; 

This will give you milliseconds between them. Some math will convert this to days, hours, minutes, seconds, or whatever you want to use. For instance:

 var seconds = totalMilliseconds / 1000; var hours = totalMilliseconds / (1000 * 3600); 

As for getting Date from string , you will need to study the constructor (check the first link) and use it the way you want. Happy coding!

+4
source

a really easy way if you always have less than 12 hours:

 a = "10:22:57"; b = "10:30:00"; p = "1/1/1970 "; difference = new Date(new Date(p+b) - new Date(p+a)).toUTCString().split(" ")[4]; alert( difference ); // shows: 00:07:03 

if you need to format more than 12 hours, this is harder to render, # MS between dates is correct using this math ...

+2
source

Source: https://habr.com/ru/post/1486716/


All Articles