简体   繁体   中英

calculate time difference in HH:mm format

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?

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

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

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM