What is the algorithm represented in Java to convert an 12 hour am/pm meridiem format hour to 24 hour format?

348 Views Asked by At

I needed to convert only the hour part of 12 hour time string to 24 hour format. I'm not interested in other than hour parts of a date string. SimpleDateFormatter is notoriously buggy and I in fact I'm more interested in the conversion algorithm itself. So what I want is to find the algorithm to convert the hour part. This is example of an uncleaned string containing hour part: "12:15PM". Sometimes there is spaces between minutes and meridiem sometimes not. Sometimes it has also character 160. So before conversion method I check and clean the string parts and then feed then meridiem(am or pm) and hour to the method which returns hour as 24 hour format int.

2

There are 2 best solutions below

2
On BEST ANSWER

This is my naive style code for beginners to convert an hour in 12 hour format to an hour in 24 format.

public static int convert12to24(String meridiem, String hour) {
    //meridiem is that am or pm,
    meridiem = meridiem.toLowerCase();
    int h_12 = 0;
    int h_24 = 0;
    try {
        h_12 = Integer.parseInt(hour);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    if (h_12 == 12) {
        //this is the midnight hour
        if (meridiem.contains("am")) {//generally before noon
            h_24 = 0;
        } else {//this is the hour starting at noon
            h_24 = 12;
        }
    } else if (h_12 >= 1)//all the rest
    {
        if (meridiem.contains("am")) {
            //hour starting after first hour at midnight to 11 facing noon
            h_24 = h_12;
        } else {//pm hours starting right after first hour after noon
            h_24 = h_12 + 12;
        }
    }

    return h_24;
}
2
On

java.time

I recommend using java.time, the modern Java date and time API, rather than your own calendar implementation. It can be used in all locales.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mma", Locale.ENGLISH);
    
    String timeString12Hours = "12:15PM";
    
    LocalTime time = LocalTime.parse(timeString12Hours, formatter);
    System.out.println("Time: " + time);
    int hour = time.getHour();
    System.out.println("Hour of day in 24 hour format: " + hour);

Output is:

Time: 12:15
Hour of day in 24 hour format: 12

What we get for free from java.time is validation. This code will detect if meridiem is not either AM or PM, or the hour is outside the range 1 through 12 or not a number at all.

Under no circumstances use the SimpleDateFormat class mentioned in the question. It’s a notorious troublemaker of a class and long outdated.

Edit: If for compatibility with old code that I don’t know and that you haven’t got time to clean up at the moment you need the method signature from your own answer:

private static DateTimeFormatter meridiemHourFormatter
        = DateTimeFormatter.ofPattern("ahh", Locale.ENGLISH);

public static int convert12to24(String meridiem, String hour) {
    String meridiemHour = meridiem + hour;
    return LocalTime.parse(meridiemHour, meridiemHourFormatter).getHour();
}

Trying it out:

    System.out.println(convert12to24("PM", "12"));

12

Every reader can decide for himself or herself: Which method implementation takes less energy to understand if in a hurry, yours or mine?

Link: Oracle tutorial: Date Time explaining how to use java.time.