Java- Convert a Degree to Clock Time


Write a Java program to convert a degree to the clock time with hour: minute format. Assume if…

Degree 0 => Time 00:00
Degree 360 => Time 12:00
Degree 90 => Time 03:00
Degree 45 => Time 01:30
Degree 250 => Time 08:20

Constraints: The degree value must be between 0-360.

Main.java
package org.websparrow;

public class Main {

    public static void main(String[] args) {

        degreeToTime(250);
        degreeToTime(0);
        degreeToTime(360);
        degreeToTime(90);
        degreeToTime(45);
    }

    private static void degreeToTime(int degree) {

        if (degree > 360 || degree < 0) throw new IllegalArgumentException("Invalid degree");

        int mod = degree % 30;
        int rem = degree / 30;
        if (mod > 0) {
            mod = mod / 5;
        }
        String result = String.format("%02d", rem) + ":" + String.format("%-2d", mod).replace(' ', '0');
        System.out.println("Degree " + degree + " ==> " + result + " hour and minutes");
    }
}

Output:

console.log
Degree 250 ==> 08:20 hour and minutes
Degree 0 ==> 00:00 hour and minutes
Degree 360 ==> 12:00 hour and minutes
Degree 90 ==> 03:00 hour and minutes
Degree 45 ==> 01:30 hour and minutes

Similar Posts

About the Author

Manish Fartiyal
Hi!, I'm Manish Fartiyal, a full-stack web application developer. I love Java and other open-source technology, currently working at one of the top MNC in India. Read all published posts by Manish Fartiyal.