I have two timestamps in HH:mm
format and I need to calculate difference between them representing the time interval in the same HH:mm
format.
Is there any utility in JavaScript to achieve this? I tried using Date
object, but I cannot find something useful... Can you help me?
and convert to seconds: var diffSeconds = diffMilliseconds / 1000; and present as HH:MM:SS using the secondsToHMS function above: secondsToHMS((date0 - date1) / 1000);
Another simple technique to calculate the duration between two times in Excel is using the TEXT function: Calculate hours between two times: =TEXT(B2-A2, "h") Return hours and minutes between 2 times: =TEXT(B2-A2, "h:mm") Return hours, minutes and seconds between 2 times: =TEXT(B2-A2, "h:mm:ss")
You can just substract two Dates from one another, the result will be the difference in milliseconds.
From the Mozilla Developer Network:
// using static methods
var start = Date.now();
// the event you'd like to time goes here:
doSomethingForALongTime();
var end = Date.now();
var elapsed = end - start; // time in milliseconds
Since Date has a constructor that accepts milliseconds as an argument, you can re-convert this to a Date by just doing
var difference = new Date(elapsed);
//If you really want the hours/minutes,
//Date has functions for that too:
var diff_hours = difference.getHours();
var diff_mins = difference.getMinutes();
Assuming tim1 is a string like "09:15" and tim2 is a string like "19:05", then the difference between tim2 and tim1 could be derived with the following javascript code :-
var tim1='09:15',tim2='19:05';
var ary1=tim1.split(':'),ary2=tim2.split(':');
var minsdiff=parseInt(ary2[0],10)*60+parseInt(ary2[1],10)-parseInt(ary1[0],10)*60-parseInt(ary1[1],10);
alert(String(100+Math.floor(minsdiff/60)).substr(1)+':'+String(100+minsdiff%60).substr(1));
Something like this:
var t1 = '12:04'.split(':'), t2 = '3:45'.split(':');
var d1 = new Date(0, 0, 0, t1[0], t1[1]),
d2 = new Date(0, 0, 0, t2[0], t2[1]);
var diff = new Date(d1 - d2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With