How to convert 24 hour format to 12 hour format through Java Program?

In Java program there is simple way to convert 24 hour format in 12 hour format and set the AM or PM tags after time.
Code to perform above task is -:

import java.util.Scanner;
public class hour_format {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int h,m;
        System.err.println("Input hours and minute");
        h=s.nextInt();
        m=s.nextInt();
        if(h<0||h>23||m<0||m>59)
            System.out.println("Invalid Input");
        else
        if (h<12)
            System.out.println(h+":"+m+" AM");
        else
        if(h==12)
            System.out.println(h+":"+m+" PM");
        else
            System.out.println((h-12)+":"+m+" PM");
    }
}

Output Screenshots-:

Leave a Reply