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

后端 未结 5 777
走了就别回头了
走了就别回头了 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 07:59

    You can use String#format with %02d on the hour portion of the String. This will pad the value with 0 until its size 2. We can then replace the original hour portion with the formatted portion.

            String timeLiteral = "2:37PM";
    
            String originalHour = timeLiteral.split(":")[0];
    
            String formattedHour = String.format("%02d", Integer.parseInt(originalHour));
    
            String result = timeLiteral.replace(originalHour, formattedHour);
    

提交回复
热议问题