Flat Preloader Icon

It's Study Time

clock

Angle between Hour and Minute hands in a clock: JavaScript

This is a very frequently asked question in interviews to write a program for following problem.

The question goes something like this: Write a program to find out the angle between the hour hand and minute hand at a given time when two inputs, Hour and Minute are given.

Lets try to understand the problem first before diving into writing the solution.

We know that a complete rotation on the clock is 360 degrees. So for every hour the hour hand will move by 360/12 degreess

Similarly for every 60 minutes the minute hand will move 360 degree. So, for every minute it will move 360/60 degrees.

This looks very simiple till now but when the minute hand moves the hour hand moves too. So for every minute the hour hand moves a little too by 360/12 ÷ 60 .

As we have all the details lets create the program in our favorite language JavaScript.

const claculateClockHandAngle = (hour, minute) => {
    const MINUTE_HAND_ANGLE_PER_MINUTE = 6, //360/60
        HOUR_HAND_ANGLE_PER_HOUR = 30, //360/12
        HOUR_HAND_ANGLE_PER_MINUTE = 0.5; //30/60

    const calculatedMinuteHandAngle = minute * MINUTE_HAND_ANGLE_PER_MINUTE;
    const claculatedHourHandAngle = hour * HOUR_HAND_ANGLE_PER_HOUR + minute * HOUR_HAND_ANGLE_PER_MINUTE;

    const angleBetweenHands = Math.abs(claculatedHourHandAngle - calculatedMinuteHandAngle);
    
    //return only acute angle
    return Math.min(360-angleBetweenHands, angleBetweenHands);
};

Share this post