Time Format Conversion | ISC Computer Science Sample Paper 2026

The 12-hour clock format (A.M./P.M.) is a time convention in which the 24 hours of the day are divided into two periods. The 24-hour clock format is the international standard.

Example: If time = 9:35 PM, then the output will be 21:35.

Write a program to accept time in 12-hour clock format (HH:MM AM/PM) and convert it to 24-hour clock format (HH:MM).

Test your program for the following data and some random data:

Example 1
INPUT: 11:30 PM
OUTPUT: 23:30

Example 2
INPUT: 12:00 AM
OUTPUT: 00:00

Example 3
INPUT: 1:45 AM
OUTPUT: 01:45

Example 4
INPUT: 12:00 PM
OUTPUT: 12:00

Example 5
INPUT: 13:30 AM
OUTPUT: INVALID INPUT

import java.util.Scanner;
class Convert{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("INPUT: ");
        String h12F = in.nextLine();
        int h = 0;
        int m = 0;
        String d = "";
        try{
            h = Integer.parseInt(h12F.substring(0, h12F.indexOf(':')));
            m = Integer.parseInt(h12F.substring(h12F.indexOf(':') + 1, h12F.indexOf(' ')));
            d = h12F.substring(h12F.length() - 2).toUpperCase();
            if(h < 1 || h > 12 || m < 0 || m > 59 || (!d.equals("AM") && !d.equals("PM")))
                throw new Exception();
        }catch(Exception e){
            System.out.println("INVALID INPUT");
            System.exit(0);
        }
        String h24F = "";
        if(d.equals("PM") && h < 12)
            h += 12;
        else if(d.equals("AM") && h == 12)
            h = 0;
        String min = m + "";
        if(min.equals("0"))
            min = "00";
        else if(min.length() == 1)
            min = "0" + min;
        String hr = h + "";
        if(hr.equals("0"))
            hr = "00";
        else if(hr.length() == 1)
            hr = "0" + hr;
        h24F = hr + ":" + min;
        System.out.println("OUTPUT: " + h24F);
    }
}