Calculate Angle Between Clock Hands


Problem: Calculate the angle between clock hands when given the number that each cock hand is at (ie. hour hand is at the 12, minute hand is at the 3, result should be 90°).

Solution 1: Calculate Angle with inputs as clock face number

public int GetAngle(int a, int b)
{
  if (a == 12) a = 0;
  if (b == 12) b = 0;
  if (a > b)
  {
    var angleTo12 = 12-a;
    var totalSections = angleTo12 + b;
    return totalSections * 30;
  }
  return (b-a)*30;
}

Solution 2: Calculate smaller angle for precise time

    public int GetAngle2(int h, int m)
    {
        if (h == 12) h = 0;
        var mAngle = m * 6;
        var hAngle = (h * 30) + (m * .5);
        return (int)Math.Abs(hAngle - mAngle);
    }

Leave a comment

Design a site like this with WordPress.com
Get started