Skip to main content
edited tags
Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237
Source Link
Drahcir
  • 255
  • 1
  • 5

Add number of hours to 24 hour clock

This function adds a number of hours to a 24 hour clock:

/**
 * @param {Integer} now The current hours
 * @param {Integer} add The number of hours to add
 */
function addHours(now, add){
    var h = (now + add) % 24;

    return h < 0 ? 24 + h : h;
};
  • addHours(2, 5) //7
  • addHours(23, 5) //4
  • addHours(23, -5) //18
  • addHours(72, 3) //3
  • addHours(0, 0) //0

The output should always be an integer in the range of 0 - 23.

I can't see any problem with it, but maybe you can. Please let me know if it can be improved or if there are any bugs.