Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate the time difference between strings in Javascript [duplicate]

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

a = "10:22:57"

b = "10:30:00"

difference = 00:07:03 ?

like image 768
user987055 Avatar asked Jun 17 '13 21:06

user987055


1 Answers

Although using Date or a library is perfectly fine (and probably easier), here is an example of how to do this "manually" with a little bit of math. The idea is the following:

  1. Parse the string, extract hour, minutes and seconds.
  2. Compute the total number of seconds.
  3. Subtract both numbers.
  4. 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

like image 78
Felix Kling Avatar answered Nov 15 '22 21:11

Felix Kling