Search code examples
javasimpledateformat

Java SimpleDateFormat convert "04:50 PM" to "16:50"


I have a question about converting from 12-hour am/pm format to 24-hour format. I have tried using SimpleDateFormat but encountered some problems.

enter image description here

As you can see, I printed 5 lines of original and converted time, but failed for cases ending with "PM". Note that some inputs are of the 24-hour format and others have the 12-hour am/pm format.

Below is the code I write for the conversion:

static String standardizeTime(String inputTime) throws ParseException {
        SimpleDateFormat[] testInputFormat = new SimpleDateFormat[2];

        SimpleDateFormat returnFormat = new SimpleDateFormat("HH:mm");
        testInputFormat[0] = new SimpleDateFormat("hh:mm aa");
        testInputFormat[1] = new SimpleDateFormat("HH:mm");
        
        testInputFormat[0].setLenient(false);
        testInputFormat[1].setLenient(false);

        Date time;
        for (int i = 0; i < testInputFormat.length; i++) {
            try {
                time = testInputFormat[i].parse(inputTime);
                return returnFormat.format(time);
            } catch (ParseException e) {
                continue;
            }
        }

        return "";
    }

What should I change to fix this problem?


Solution

  • This works as expected.

    import java.text.SimpleDateFormat;
    
    public class HelloWorld{
    
         public static void main(String []args) throws Exception {
             final SimpleDateFormat parser = new SimpleDateFormat("hh:mm aa");
             final SimpleDateFormat printer = new SimpleDateFormat("HH:mm");
            System.out.println(printer.format(parser.parse("4:07 pm")));
         }
    }
    

    Your code looks good so I think problem is elsewhere.