Home » Convert 12 hours to 24 hours in java

Convert 12 hours to 24 hours in java

  • by
Convert 12 hours to 24 hours in java

1. Overview

In this article, we will learn to convert 12 hours to 24 hours in Java. To learn more about other Java topics, refer to these articles.

2. Convert 12 hours to 24 hours in java

Assume we have asked you to convert a time in hour AM/PM format to military (24-hour) time.

Note: 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.

For example,

  • Return ’12:01:00′.
  • Return ’00:01:00′.

Let’s create a timeConversion function in the editor below. It takes a date string (12- hours) as input and returns a new string representing the input time in a 24-hour format.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
class Result {
    private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mm:ssa");
    private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm:ss");
    public static String timeConversion(String s) {
        try {
            return TWENTY_FOUR_TF.format(
                    TWELVE_TF.parse(s));
        } catch (ParseException e) {
            return s;
        }
    }
}

Let’s decipher the above code.

We have converted the string to Date object by using DateFormat.parse function. Later, we use the format function to convert the Date to the specified 24-hour format pattern.

The SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (converts date to text), and parsing (converts the string to date object).

You can refer to this link to understand the date and time patterns. Below are the patterns used in this example for conversion.

  • m - minute
  • s - second
  • h - Hour in am/pm (1-12)
  • a - am or pm marker
  • H - Hour in day (0-23)

3. Conclusion

To sum up, we have learned to convert 12 hours to 24 hours format. You can find code samples in our GitHub repository.

Leave a Reply

Your email address will not be published.