9

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?

1

4 Answers 4

26

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();
4
  • How can I parse a HH:mm string to a Date object?
    – davioooh
    Commented Aug 30, 2012 at 9:07
  • Have you read the MDN Date API? There are a lot of ways, but two spring to mind: use the new Date(year, month, day [, hour, minute, second, millisecond]) constructor, or create a new Date and use setHours & setMinutes.
    – Konerak
    Commented Aug 30, 2012 at 9:24
  • 1
    How do i get time diffrence between date = "2016/03/01 11:00" to date ="2016/03/06 11:00" Commented Feb 25, 2016 at 7:28
  • 2
    I recommend using getUTCHours() and getUTCMinutes() instead, in order to handle timezone issues.
    – beta
    Commented May 18, 2017 at 7:29
7

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);
1
  • i prefer something like this code var t1 = jstart.split(":"); var t2 = jstop.split(":"); var min_1 = parseInt(t1[0]) * 60 + parseInt(t1[1]); var min_2 = parseInt(t2[0]) * 60 + parseInt(t2[1]); console.log((min_2-min_1)); code Commented Feb 29, 2020 at 4:06
1

You could try this

https://github.com/layam/js_humanized_time_span

and format the output?

or if using jquery you can try

http://timeago.yarp.com/

1

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));

Not the answer you're looking for? Browse other questions tagged or ask your own question.