Find angle between hour hand and minute hand in JavaScript

Hi there. Today we will see how to calculate the angle(in degrees) between the hour hand and minute hand of a clock using javascript. We will write our code such that you can use both 12-hour and 24-hour clock notations. We will use javascript for coding this. So, it will be very easy to understand.

The main concept here is that the minute hand moves 360 degrees in 60 minutes(6 degrees in 1 minute) and hour hand moves 360 degrees in 12 hours(30 degrees in 1 hour). Also, the hour hand moves 0.5 degrees per minute. We will calculate the difference between their current angles. Now, let’s go to the programming part.

We will pass 3 parameters to our function. The 3rd one is optional. It denotes if the clock notation we are using is 12-hour notation or 24-hour notation. But even if you don’t pass it, the program will run without any problems. We will also check the working using some test cases after writing the function. Now, let’s look at our JS code:

function angle(h, m, check) { 
  h = h % 12;
  var hm = 0.5 * m, 
      hh = 30 * h, 
      ma = 6 * m, 
      sum = Math.abs(hm + hh - ma); 

  return check ? 360 - sum : sum;

//test cases

console.log("12:01", angle(12, 01)); 
console.log("12:00", angle(12, 00)); 
console.log("16:42", angle(16, 42)); 
console.log("11:01", angle(11, 01)); 
console.log("4:42", angle(4, 42)); 
console.log("4:42", angle(4, 42, true)); 
console.log("00:01", angle(00, 01)); 
console.log("24:01", angle(24, 01));

Now, let’s look at the output of these test cases.

12:01 5.5
12:00 0
16:42 111
11:01 324.5
4:42 111
4:42 249
00:01 5.5
24:01 5.5

The program first prints the time, and then the angle between the hour and minute hand. The angle is calculated in degrees.

I hope you found this article useful. There are some more interesting clock topics that you can explore. For example, try to calculate the time when both the hands are coinciding. Or maybe try to code a time notation converter.

Leave a Reply
