0

I don't find any docs about it on moment.js website. I need to calculate difference from 2 duration time (not dates). For example:

27:10 - 7:20 = 19:50

where 27 is hours (can be bigger than 24h of a day) and 10 is minutes.

I see moment.js can operatore only with dates?

Giuseppe Lodi Rizzini
  • 1,045
  • 11
  • 33

4 Answers4

2

You can use moment.duration()

var d1, d2, dDiff, diff;  
d1 = moment.duration('7:20', 'HH:mm');
d2 = moment.duration('27:10', 'HH:mm');

dDiff = d2.subtract(d1);

diff = dDiff.get('days') + ':day(s) ' + dDiff.get('hours') + ':' + dDiff.get('minutes');

console.log(diff); // "0:day(s) 19:50"

more details: momentjs durations

jacob devs
  • 31
  • 3
1

function getTimeDifference(start, end) {
        var s = start.split(':');
        var e = end.split(':');
        var d = (parseInt(s[0], 10) * 60 + parseInt(s[1], 10)) - (parseInt(e[0], 10) * 60 + parseInt(e[1], 10));
        var res = parseInt((d / 60), 10).toString() + ':' + (d % 60).toString();
        alert(res);
    }
    getTimeDifference('27:10' , '7:20');

May be helpful to you...

Divyesh patel
  • 967
  • 1
  • 6
  • 21
1

This doesn't need a library, you just need to do some base60 arithmetic.

You simply convert both to minutes, do a subtraction and convert back to hours and minutes

//27:10 - 7:20 = 19:50

function calculateDifference(time1,time2){
    
    var diffMins = toMinutes(time1)-toMinutes(time2);
    return toHoursMinutes(diffMins);
}

function toMinutes(time){
    var [hrs,mins] = time.split(':').map(x => parseInt(x,10));
    return hrs*60 + mins;
}

function toHoursMinutes(mins)
{
    return Math.floor(mins/60) + ":" + (mins%60).toString().padStart('0',2);
}

console.log(calculateDifference("27:10","7:20"));
Jamiec
  • 133,658
  • 13
  • 134
  • 193
1

You can do it using pure maths

function f1(a, b) {
    const [hoursA, minutesA] = a.split(':').map(v => parseInt(v, 10));
    const [hoursB, minutesB] = b.split(':').map(v => parseInt(v, 10));
    let minutesDiff = 60 * (hoursA - hoursB) + (minutesA - minutesB)
    const hoursDiff = (minutesDiff - minutesDiff % 60) / 60;
    minutesDiff = minutesDiff % 60;
    return hoursDiff + ':' + minutesDiff.toString().padStart(2,'0');
}
console.log(f1('27:10','7:20'))
console.log(f1('248:10','7:05'))

or using the date object

function f2(a, b) {
    const [hoursA, minutesA] = a.split(':').map(v => parseInt(v, 10));
    const [hoursB, minutesB] = b.split(':').map(v => parseInt(v, 10));
    const time = new Date(Date.UTC(1970));
    time.setUTCHours(hoursA - hoursB, minutesA - minutesB);
    return ((time - time % 86400000) / 3600000 + time.getUTCHours()) + ':' + time.getUTCMinutes().toString().padStart(2,'0');
}
console.log(f2('27:10','7:20'))
console.log(f2('248:10','7:05'))
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87