Java parsing datetime from 12-hr format to 24-hr [closed]



I have this datetime sample 21-SEP-21 11.36.59.000 PM that I want to convert it by Java code to 24-hour format to the format "yyyy-MM-dd HH:mm:ss". I have tried the below code, but still didn’t work:

public static String timestamp_conversion(String input) {
    if (!input.equals("")) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy HH.mm.ss.SSS" );
        LocalDateTime localDate = LocalDateTime.parse(input, formatter);
        
        String return_date = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss")
                                              .format(localDate);
        return return_date;
    } else {
        return input;
    }
}

I want the correct parsing format for the above sample.

Answer

You have to use lower-case hh as the symbol for the hour of day in the pattern used to read/parse the input. In order to be able to distinguish ante meridiem (AM) from post meridiem (PM), you should include a, too. That would parse a full 12h format including AM/PM notation.

If you use the upper-case HH, you will have the 24h format.

You will also have to pay attention to the Locale used here and possibly to the fact that your abbreviation of the name of the month is in upper-case characters only.

See this alternative to the code you posted:

public static String timestampConversion(String input) {
    if (!input.equals("")) {
        // build up a formatter with the correct symbol for hour of day
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                            // let it parse month names in upper case
                                            .parseCaseInsensitive()
                                            // using the desired pattern
                                            .appendPattern("dd-MMM-yy hh.mm.ss.SSS a")
                                            // in the desired locale
                                            .toFormatter(Locale.ENGLISH);
        LocalDateTime localDate = LocalDateTime.parse(input, formatter);
        // use the correct symbols for hour of day in 24h format (HH)
        String returnDate = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss",
                                                        // and a locale
                                                         Locale.ENGLISH)
                                              .format(localDate);
        return returnDate;
    } else {
        return input;
    }
}

Using it in a main like this

public static void main(String[] args) throws IOException {
    String someTime = "21-SEP-21 11.36.59.000 PM";
    System.out.println(timestampConversion(someTime));
}

will give you the output

2021-Sep-21 23:36:59


Source: stackoverflow