JavaScript: Clock Angle Problem
Earlier today I was presented with the problem of calculating the degrees between the hour hand and the minute hand of an analog clock. At first this seemed like a fairly complicated task, however after playing with it for a bit the solution became apparent. But now after looking up the answer on Google I feel really embarrassed on how easy the solution really is.
It’s amazing how complicated you can make a solution, when most of the time it can be solved so easily once you have the basic logic worked out.
Solution:
// h = 1..12, m = 0..59
function angle(h,m) {
hAngle = 0.5 * (h * 60 + m);
mAngle = 6 * m;
angle = Math.abs(hAngle - mAngle);
angle = Math.min(angle, 360 - angle);
return angle;
}