1

I have jquery hours range picker and I am not using 'am' & 'pm' notation. I prefer 24h. I need to calculate the hours difference between selected hours.

User selects '09:00' & '12:00' -> 3 hours

My problem is with if he selects '20:00' & '00:00' -> must be 4 hours but gives negative. Alternatively; '23:00' & '02:00' -> negative

Should I take abs? or any other way?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Shalafister's
  • 761
  • 1
  • 7
  • 34

2 Answers2

1

You need to use modulo. Unfortunately Javascript's modulo is wrong.

Number.prototype.mod = function(n) {
    return ((this % n) + n) % n;
};

console.log((0 - 20).mod(24));
Jack
  • 804
  • 7
  • 18
1

Simply add if check to the difference you get and if it's negative add 24 hours to it

var diff = function(a,b) {
  var difference = b - a;
  if (difference < 0) {
    return difference + 24;
  } else {
    return difference;
  }
}

Of course you will need to parse your time first. Here is a fiddle with alerts instead of returns. But this is the easiest way i guess, but mb not the best one fiddle

JSEvgeny
  • 2,550
  • 1
  • 24
  • 38
  • 1
    Downvote isn't mine, but you have missed a `)` and you don't return anything outside of the `if` statement. Also some description of the problem and why this fixes it would help to educate the OP and any future visitors to this question – Rory McCrossan Jan 20 '17 at 10:05