Time Conversion in Java

In this tutorial, we are going to learn Time conversion in Java (i.e) how we can convert 12-hour time notation to 24-hour time notation. In simple words given a time in 12-hour AM/PM format, we’ll convert it to military (24-hour) time. So what is 24-hour time notation?

A 24-hour clock is a way of telling the time in which time is divided into 24 hours and is numbered from 0 to 24. It does not use a.m. or p.m. It is also called as military time, continental time or railway time.

 

Note: Midnight is 12:00:00 AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.

Code for implementing Time conversion in Java

import java.util.*;
class time
{
  public static void main(String[]args) {      

    Scanner scan = new Scanner(System.in);
    String time = scan.next();

    //splitting the string in parts when we encounter ":" in the string
    String tArr[] = time.split(":");
    String AmPm = tArr[2].substring(2,4);
    int hh,mm,ss;

    //converting the strings to integers
    hh = Integer.parseInt(tArr[0]);
    mm = Integer.parseInt(tArr[1]);
    ss = Integer.parseInt(tArr[2].substring(0,2));
        
    String checkPM = "PM",checkAM ="AM";
       
    if(AmPm.equals(checkAM) && hh==12)
    {
      	hh=0;
    }
    else if(AmPm.equals(checkPM)&& hh<12)
    {
      	hh+=12;
    }
        
    System.out.printf("%02d:%02d:%02d",hh,mm,ss);

  }
}

Output:

12:00:00AM
00:00:00
07:05:45PM
19:05:45
12:45:54PM
12:45:54

Explanation

  1. We scan the input string and split the string into individual numbers when encountering a colon (:) using the split function.
  2. Next, we convert the number strings to integers using the Integer.parseInt() function.
  3.  Then we check the meridian using equals function and perform the respective operations.

Note: %02d means: 2 digits and left padding with zeros.
Example 1: If the number is 7 then %02d formats it as 07.
Example 2: If the number is 54 then %02d formats it as 54.

Hope you’ve understood the code 🙂
Any questions feel free to drop in your comments.

You can also check other posts:

Leave a Reply

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