How To Convert Time From 12 Hour To 24 Hour In Java Console Menu Driven User Interface

How To Convert Time From 12 Hour To 24 Hour In Java Console Menu Driven User Interface

TwelveHourToTwetyFourHour.java

This is a menu driven Java program that prompts user to enter hours, minutes seconds AM/PM and converts the time to 24 hour clock format..

Console Menu Driven User Interface SOURCE CODE

TwelveHourToTwetyFourHour.java

/*
 * How To Convert Time From 12 Hour To 24 Hour In Java Console Menu Driven User Interface
 * https://mauricemuteti.info/how-to-convert-time-from-12-hour-to-24-hour/
 */
package pkg12to24hoursconvertor;

import java.util.Scanner;

/**
 *
 * @author HP
 */
public class TwelveHourToTwetyFourHour {

    private static Scanner keyboard;

    public static void main(String[] args) {
        //Creating Scanner Object
        keyboard = new Scanner(System.in);
        //Creating hour variable and invoking getHours() Static Method To prompt for user input.
        int hr = getHours();
        //Creating minute variable and invoking getMinutes() Static Method To prompt for user input.
        int min = getMinutes();
        //Creating second variable and invoking getSeconds() Static Method To prompt for user input.
        int sec = getSeconds();
        //Declaring am pm string variable.
        String amOrPm;

        keyboard.nextLine();
        System.out.print("Enter AM or PM: ");
        //Prompting user to enter either am or pm.
        amOrPm = keyboard.nextLine();
        //Invoking print24HourTime Static Method to convert time to 24 hours and print the output on the keyboard.
        //Arguments passed are hours, minutes, seconds, am/pm.
        print24HourTime(hr, min, sec, amOrPm);

    }

    /**
     * Method for getting hours from user input and validating the input.
     *
     * Hours must range from zero to 12. Anything out of that range throws a
     * custom exception.
     *
     * @return
     */
    public static int getHours() {

        //Creating hours variable.
        int hours = 0;
        //Creating success boolean variable.
        boolean success = false;
        //While loop - this loops until user enters a value in the range between 0 and 12.
        while (!success) { //Loop so long as success variable is not true
            //try catch block.
            try {
                //Printing Enter hours on the console.
                System.out.print("Enter hours: ");
                hours = keyboard.nextInt(); // get hours from user input
                if (hours >= 0 && hours <= 12) // check hours is between 0 and 12 or not
                {
                    //Changing success value to true.
                    success = true;
                } else {
                    //Thowing exception.
                    throw new InvalidHrExcep("The value of hours must be between 0 and 12."); // throw exception
                }
            } catch (InvalidHrExcep e) {
                System.out.println(e); // print (InvalidHrExcep) exception message
            }
        }
        return hours; // return hour
    }

    /**
     * Method for getting minutes from user input and validating the input.
     *
     * This method gets user in put from the console and loops until user enters
     * values within the required range.
     *
     * @return
     */
    public static int getMinutes() {

        //Creating minutes variable.
        int minutes = 0;
        boolean success = false;
        //While loop - this loops until user enters a value in the range between 0 and 60.
        while (!success) { //Loop so long as success variable is not true
            try {
                System.out.print("Enter minutes: ");
                minutes = keyboard.nextInt(); // get minutes from user input
                if (minutes >= 0 && minutes <= 60) // check minutes is between 0 and 60 or not
                {
                    success = true;
                } else {
                    throw new InvalidMinExcep("The value of minutes must be between 0 and 60."); // throw exception
                }
            } catch (InvalidMinExcep e) {
                System.out.println(e);// print (InvalidMinExcep) exception message
            }
        }
        return minutes; // return minutes

    }

    /**
     * Method for getting seconds from user input and validating the input.
     *
     * @return
     */
    public static int getSeconds() {

        //Creating seconds integer variable.
        int seconds = 0;
        boolean success = false;
        while (!success) { //Loop so long as success variable is not true
            try {
                System.out.print("Enter seconds: ");
                seconds = keyboard.nextInt(); // get seconds from user input
                if (seconds >= 0 && seconds <= 60) // check seconds is between 0 and 60 or not
                {
                    success = true;
                } else {
                    throw new InvalidSecExcep("The value of minutes must be between 0 and 60."); // throw exception
                }
            } catch (InvalidSecExcep e) {
                System.out.println(e);// print (InvalidSecExcep) exception message
            }
        }
        return seconds; // return second
    }

    /**
     * Method for converting time to 24 hour clock.
     *
     * @param hr
     * @param min
     * @param sec
     * @param str
     */
    public static void print24HourTime(int hr, int min, int sec, String str) {

        //checking if Minutes is less than 10 in order to add zero prefix to the minutes.
        String zeroPrefixForMinutes = min < 10 ? "0" : "";
        //checking if Seconds is less than 10 in order to add zero prefix to the seconds.
        String zeroPrefixSeconds = sec < 10 ? "0" : "";
        //Check if the str argument is either PM or AM.
        if (str.toUpperCase().equals("AM")) {
            //If the hour is 12 change it to 0 so that it displays 00:00:00(Hours:minutes:Seconds). 
            //This block changes 12 to 00 to imitate normal clock.
            if (hr == 12) {
                //if hour is 12 change it to zero.
                hr = 0;
            }
            //checking if hour is less than 10 in order to add zero prefix to the hour.
            String zeroPrefixForAM = hr < 10 ? "0" : "";
            //Printing AM On the console
            System.out.println("24 Hour Clock Time: " + zeroPrefixForAM + hr + ":" + zeroPrefixForMinutes + min + ":" + zeroPrefixSeconds + sec);
            //if the str argument value is PM.
        } else if (str.toUpperCase().equals("PM")) {
            //Printing PM On the console
            System.out.println("24 Hour Clock Time: " + (hr + 12) + ":" + zeroPrefixForMinutes + min + ":" + zeroPrefixSeconds + sec);
        } else {
            //If user enters invalid PM AM output this message on the console.
            System.out.println("Invalid AM or PM");
        }
    }
}

InvalidHrExcep.java

 /*
 * How To Convert Time From 12 Hour To 24 Hour In Java Console Menu Driven User Interface
 * https://mauricemuteti.info/how-to-convert-time-from-12-hour-to-24-hour/
 */
package pkg12to24hoursconvertor;

/**
 *
 * @author HP
 */
public class InvalidHrExcep extends Exception {

    private String message;

    public InvalidHrExcep() {

    }

    /**
     *
     * @param str
     */
    public InvalidHrExcep(String str) {

        str = message;

    }

    public String getmessage() {

        return message;

    }

    /**
     *
     * @return
     */
    @Override
    public String toString() {

        return String.format("The value of hours must be between 0 and 12.");

    }

}
 

InvalidMinExcep.java

 /*
 * How To Convert Time From 12 Hour To 24 Hour In Java Console Menu Driven User Interface
 * https://mauricemuteti.info/how-to-convert-time-from-12-hour-to-24-hour/
 */
package pkg12to24hoursconvertor;

/**
 *
 * @author HP
 */
public class InvalidMinExcep extends Exception {

    private String message;

    public InvalidMinExcep() {

    }

    /**
     * 
     * @param str 
     */
    public InvalidMinExcep(String str) {

        str = message;

    }

    public String getmessage() {

        return message;

    }

    /**
     * 
     * @return 
     */
    @Override
    public String toString() {

        return String.format("The value of minutes must be between 0 and 60.");

    }

}
 

InvalidSecExcep.java

 /*
 * How To Convert Time From 12 Hour To 24 Hour In Java Console Menu Driven User Interface
 * https://mauricemuteti.info/how-to-convert-time-from-12-hour-to-24-hour/
 */
package pkg12to24hoursconvertor;

/**
 *
 * @author HP
 */
public class InvalidSecExcep extends Exception {

    private String message;

    public InvalidSecExcep() {

    }

    /**
     * 
     * @param str 
     */
    public InvalidSecExcep(String str) {

        str = message;

    }

    public String getmessage() {

        return message;

    }

    /**
     * 
     * @return 
     */
    @Override
    public String toString() {

        return String.format("The value of seconds must be between 0 and 60.");

    }

}
 

NEBEANS IDE OUTPUT

run:
Enter hours: 12
Enter minutes: 7
Enter seconds: 8
Enter AM or PM: AM
24 Hour Clock Time: 00:07:08
BUILD SUCCESSFUL (total time: 2 minutes 44 seconds)

NETBEANS OUTPUT 2

run:
Enter hours: 12
Enter minutes: 6
Enter seconds: 7
Enter AM or PM: PM
24 Hour Clock Time: 24:06:07
BUILD SUCCESSFUL (total time: 7 seconds)

SCREENSHOTS

How To Convert Time From 12 Hour To 24 Hour In Java Console Menu Driven User Interface

VIDEO TUTORIAL/DEMO

Leave a Reply

Your email address will not be published. Required fields are marked *