7

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 ?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
user987055
  • 1,039
  • 4
  • 14
  • 25
  • create two diff date objects, subtract the smaller from the larger(or use Math.abs() to ensure you get a positive number), convert ms to hours:min:seconds – Kevin B Jun 17 '13 at 21:42
  • 1
    A little bit of search wouldn't hurt...[This for knowing how convert String into Date](http://stackoverflow.com/questions/5619202/converting-string-to-date-in-js) and [this for subtracting two dates/time one from another](http://stackoverflow.com/questions/1787939/check-time-difference-in-javascript) – RaphaelDDL Jun 17 '13 at 21:43
  • 2
    Handling dates and times in Javascript is enough to drive strong men to drink. It's one of those times when "use a library" might well be the right response if you have anything even vaguely complex that you need to do. – lonesomeday Jun 17 '13 at 21:43
  • consider a library indeed, something like this might do the trick https://github.com/timrwood/moment – Pevara Jun 17 '13 at 21:46
  • @Koki w3schools is a terrible resource. Use MDN – John Dvorak Jun 17 '13 at 22:00

4 Answers4

15

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
4

Make two Date objects out of them. Then you can compare.

Get the value out of both dates you wish to compare, and make a subtraction. Like this (supposing foo and bar are dates):

var totalMilliseconds = foo - bar;

That will give you the amount of milliseconds between both. Some math will convert that to days, hours, minutes, seconds or whatever unit you wish to use. For example:

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

As for obtaining a Date from a string, you'll have to look into the constructor (check the first link), and use it in the way that suits you best. Happy coding!

Geeky Guy
  • 9,229
  • 4
  • 42
  • 62
3

a really easy way if you will always have fewer 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 for more than 12 hours, it's more complicated to render, the # of MS between the dates is correct using the this math...

dandavis
  • 16,370
  • 5
  • 40
  • 36
0

You have to use Date objects : http://www.w3schools.com/jsref/jsref_obj_date.asp

Then compare : How to calculate date difference in javascript

Community
  • 1
  • 1
flow
  • 4,828
  • 6
  • 26
  • 41
  • 4
    http://www.w3fools.com/ -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – Kevin B Jun 17 '13 at 21:44