Given a Date
(in JS and Ruby) or hours
and minutes
(in C and Python), return the angle between the two hands of a 12-hour analog clock in radians.
Notes:
- The minute hand always points to the exact minute (there is no seconds hand).
- The hour hand does not «snap» to the tick marks: e.g. at
6:30
the angle is not0
because the hour hand is already half way between6
and7
. - Return the smaller of the angles ( <= π ).
- Return
π
if the hands are opposite.
Examples
- at noon the angle is:
0
- at
3:00
the angle is:π/2
(90 degrees) - at
6:00
the angle is:π
(180 degrees) - at
9:00
the angle is:π/2
(90 degrees)
Solution
JavaScript
function handAngle (date) {
const PI = 3.141592653589793;
const hour = date.getHours();
const min = date.getMinutes();
let angle = Math.abs((hour * 30 + min * 0.5) - (min * 6));
angle = angle < 180 ? angle : 360 - angle;
return PI * angle / 180;
}