# 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
*/
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.

• Other that the inappropriate parameter name now, there is not much you could say about it code-wise. However what I'd like to question its usefulness, which seems very limited. – RoToRa Jul 3 '14 at 13:02
• @RoToRa I'm using as part of a set of unit tests. I have to test some other functions that manipulate time, and this one helps keep the tests readable. – Drahcir Jul 3 '14 at 13:17

Tiny question ;)

• As @Rotora mentioned, now is not a fantastic parameter name, it conveys that I need to only pass who late it is 'now', add is a verb, also not brilliant as parameter naming goes

• addHours( -500 , -100 ) returns -0, is that what you want ?

• You have 4 lines of comment, 3 lines of code, 1 blank line, perhaps you have to much comment ? Try to not need comments by working harder on parameter names.

• Since adding is commutative ( order does not matter ), I would consider naming the function sumHours and name the parameters hours1 and hours2

function sumHours(hours1, hours2){
var sum = (hours1 + hours2) % 24;
return sum < 0 ? 24 + sum : +sum;
};

• Thanks for finding the -0 bug, actually I didn't know -0 was even a number. Also your other points are helpful. – Drahcir Jul 3 '14 at 13:29
• Negative zero might not be that big of a problem for you, as it behaves very much like positive zero. You would have to go out of your way to test 1 / -0 === Number.NEGATIVE_INFINITY to detect negative zero. – 200_success Jul 5 '14 at 1:12