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
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);