简体   繁体   中英

Difference between two times (not dates) in format (hh:mm)

For example I have these two times as string:

Time_A = "07:35" (means 7 hours and 35 minutes)

Time_B = "15:00" (means 15 hours and 00 minutes)

Now I would like to substract the Time_B from Time_A. This should return "-07:25" (means minus 7 hours and 25 minutes) Therefore I tried using the following function:

function time_diff(Time_A,Time_B ) {

           var t1parts = t1.split(':');
           var t1cm = Number(t1parts[0]) * 60 + Number(t1parts[1]);

           var t2parts = t2.split(':');
           var t2cm = Number(t2parts[0]) * 60 + Number(t2parts[1]);

           var hour = Math.floor((t1cm - t2cm) / 60);
           var min = Math.floor((t1cm - t2cm) % 60);
           return (hour + ':' + min + ':00');
}

But this function is returning: -8:-25:00 instead of -07:25:00. Any idea how to fix this?

It's because you are rounding a negative number down:

Math.floor(-455/60) = Math.floor(-7.4166667) = -8

You could do:

var diff = Math.abs(t1cm - t2cm);
var hour = Math.floor(diff / 60);
var min = diff % 60;

return (t1cm < t2cm ? '-' : '') + hour + ':' + min + ':00';

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