Core Java

Convert 12-Hour Time into a 24-Hour Time Format using Java

Converting time from the 12-hour clock format to the 24-hour clock format is a common programming task, particularly when dealing with scheduling, time tracking, or data processing. To convert between time format simplifies time-related calculations and ensures consistency in time representation in Java programs. In this guide, we will explore how to achieve this conversion in Java.

1. Understanding Time Formats

Before we embark on the Java code, it’s essential to understand the differences between the 12-hour and 24-hour time formats.

1.1 The 12-Hour Format

The 12-hour format uses numbers from 1 to 12 to represent hours. In this format, time is represented with two periods: AM (Ante Meridiem) and PM (Post Meridiem).

1.2 The 24-Hour Format

The 24-hour format uses a continuous numbering system from 00 to 23 to represent hours and is known as military time or the international time format.

As an example, 1:30 PM in the 12-hour time format corresponds to 13:30 in the 24-hour time format.

2. Using SimpleDateFormat Class

In Java, you can perform the conversion from 12-hour time to 24-hour time format by utilizing the SimpleDateFormat class found within the java.text package. Here’s an example code of how to do this:

public class ConvertTo24HourFormat {

    public static String convertTo24HourFormat(String time12Hour) {
        try {
            // Create a SimpleDateFormat object for parsing 12-hour time.
            SimpleDateFormat twelveHourFormat = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);

            // Create a SimpleDateFormat object for formatting 24-hour time.
            SimpleDateFormat twentyFourHourFormat = new SimpleDateFormat("HH:mm");
            

            // Parse the 12-hour time and format it as 24-hour time.
            Date twelveHourTime = twelveHourFormat.parse(time12Hour);
            String twentyFourHourTime = twentyFourHourFormat.format(twelveHourTime);

            return twentyFourHourTime;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        
        String time12Hour = "01:30 PM";
        String time24Hour = convertTo24HourFormat(time12Hour);
        
        if (time24Hour != null) {
            System.out.println("12-Hour Time: " + time12Hour);
            System.out.println("24-Hour Time: " + time24Hour);
        } else {
            System.out.println("Invalid time format.");
        }
    }
}

In the above code, we start by creating a method called convertTo24HourFormat which performs the conversion. The convertTo24HourFormat method takes a 12-hour time string as input and returns the equivalent time in 24-hour format as a string.

Inside the method, we create Two SimpleDateFormat object. The first one named twelveHourFormat is used for parsing the 12-hour time string into a Date object while the second one named twentyFourHourFormat is then used for formatting the Date object into a 24-hour time.

We then use the conversion method by calling it in our main method. It passes a 12-hour time string (01:30), converts it to a 24-hour time format, and then prints both the original and converted times. The output from running the above code is:

Fig 1: Output - convert 12-hr time format to 24-hr time format using SimpleDateFormat class in Java
Fig 1: Output – convert 12-hr time format to 24-hr time format using SimpleDateFormat class in Java

3. Using the Date Time API

In Java 8, the Date Time API introduces a class that allows for time formatting using various patterns. Below is an example code to convert from 12-hour time to 24-hour time format using the Java Date Time API:

public class ConvertTo24HrDateTimeAPI {

    public static String convertTo24HourFormat(String time12Hour) {
        try {
            // Define a DateTimeFormatter for parsing 12-hour time.
            DateTimeFormatter twelveHourFormatter = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);

            // Parse the input 12-hour time string.
            LocalTime twelveHourTime = LocalTime.parse(time12Hour, twelveHourFormatter);

            // Create a DateTimeFormatter for formatting the result as 24-hour time.
            DateTimeFormatter twentyFourHourFormatter = DateTimeFormatter.ofPattern("HH:mm");

            // Format the time in 24-hour format and return it as a string.
            return twelveHourTime.format(twentyFourHourFormatter);
        } catch (DateTimeParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String time12Hour = "01:30 PM";
        String time24Hour = convertTo24HourFormat(time12Hour);
        if (time24Hour != null) {
            System.out.println("12-Hour Time: " + time12Hour);
            System.out.println("24-Hour Time: " + time24Hour);
        } else {
            System.out.println("Invalid time format.");
        }
    }
}

In the above code, we start by creating a method named convertTo24HourFormat that performs the conversion. Inside the method, A DateTimeFormatter named twelveHourFormatter is defined with the pattern hh:mm a for parsing the 12-hour time. Note that the a in the pattern indicates AM or PM.

Next, a 12-hour time string named time12Hour is parsed into a LocalTime object using twelveHourFormatter. Another DateTimeFormatter named twentyFourHourFormatter is defined with the pattern HH:mm for formatting the result in 24-hour time.

Finally, we call our conversion method in the main method by passing a 12-hour time string 01:30 PM. The output from running the above code is:

12-Hour Time: 01:30 PM
24-Hour Time: 13:30

4. Conclusion

In this article, we explored two different methods for transforming time from the 12-hour time format into the 24-hour time format. In conclusion, Java makes it relatively straightforward to convert time from 12-hour to a 24-hour format using the SimpleDateFormat class and the newer Date Time API introduced in Java 8.

5. Download the Source Code

This was an example of Converting 12-hour Time into a 24-hour Time Format using Java.

Download
You can download the full source code of this example here: Convert 12-Hour Time into a 24-Hour Time Format using Java

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button