I am working on a small script using momentjs, that shows me how many hours and minutes (seperate) I have until a specific hour. But for some reason the result is wrong.
Thats my code so far:
var TimeA = moment('08:00:00', 'HH:mm:ss');
var TimeB = moment('16:00:00', 'HH:mm:ss');
var DiffAB = moment(TimeA.diff(TimeB)).format('HH:mm:ss');
var DiffHours = moment(DiffAB, 'HH:mm:ss').format('H');
var DiffMinutes = moment(DiffAB, 'HH:mm:ss').format('mm');
console.log('TimeA: ' + moment(TimeA).format('HH:mm:ss'));
console.log('TimeB: ' + moment(TimeB).format('HH:mm:ss'));
console.log('Difference A-B: ' + DiffAB);
console.log('Diff Hours: ' + DiffHours);
console.log('Diff Minutes: ' + DiffMinutes);
And thats the Output:
TimeA: 08:00:00
TimeB: 16:00:00
Difference A-B: 17:00:00
Diff Hours: 17
Diff Minutes: 00
The difference of A - B should be 8 but its showing 17.
As per momentjs documentation
If the moment is earlier than the moment you are passing to moment.fn.diff, the return value will be negative.
To translate it to your example:
If TimeA is earlier than TimeB passed to moment.diff then the value will be negative
and since it's returned as milliseconds -28800000 is an instruction like: take that amount of miliseconds from midnight, that gives you the different time
so what you should be doing is
var DiffAB = moment(TimeB.diff(TimeA)).utcOffset(0).format('HH:mm:ss');
Diff documentation https://momentjs.com/docs/#/displaying/difference/
Example from doc
An easy way to think of this is by replacing .diff( with a minus operator.
// a < b
a.diff(b) // a - b < 0
b.diff(a) // b - a > 0
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