How to parse a 1 or 2 digit hour string with Java?

后端 未结 5 778
走了就别回头了
走了就别回头了 2021-01-29 07:37

My parser may encounter \"2:37PM\" (parsed by \"H:mma\") or \"02:37PM\" (parsed by \"hh:mma\"). How can I parse both without resorting to a try-catch?

I receive an erro

5条回答
  •  既然无缘
    2021-01-29 08:02

    You did say you wanted to parse the string. So you can do the following.

    for (String s : new String[] { "02:37PM", "2:37PM" }) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h:mma");
        LocalTime lt = LocalTime.parse(s, dtf);
        System.out.println(lt.format(dtf));
    }
    

    Prints

    2:37PM
    2:37PM
    
    

提交回复
热议问题