javadatetime-formatdatetime-conversiontimeofday

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


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.


Solution

  • 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;
    }