Chenya Zhang Chenya Zhang - 3 months ago 16
Java Question

Parsing time with DateTimeFormatter "hh:mm a" cause Exception

I have already checked many solutions online but still got the exception when parsing "hh:mm a".

In JSP:

$('#t2').timepicker({
timeFormat : 'hh:mm a',
interval : 30,
maxTime : '11:00 pm',
startTime : '08:00 am',
dynamic : false,
dropdown : true,
scrollbar : true
});

...

<div class="form-group">
<label
class="col-md-3 control-label">Start
Time</label>
<div class="col-md-7">
<input type="text"
class="timepicker"
id="t1"
name="startTime"
readonly="readonly">
</div>
</div>


In Java:

String startTime = request.getParameter("startTime");
DateTimeFormatter formatterTime1 = DateTimeFormatter.ofPattern("hh:mm a", Locale.US);
LocalDateTime localStartTime = LocalDateTime.parse(startTime, formatterTime1);


Exception:

java.time.format.DateTimeParseException: Text '08:00 am' could not be parsed at index 6


Even when I tried to hardcode:

String startTime = "08:00 am" (08:00am, 8:00am);


It has the same problem.
Even in a single test file.
Is it because Java 8 cannot parse time only String?

Answer

In addition to Meno's answer, you'll need uppercase AM or PM or a case insensitive DateTimeFormatter, which you can build as

String startTime = "08:00 am";
DateTimeFormatter formatterTime1 = new DateTimeFormatterBuilder()
   .parseCaseInsensitive().appendPattern("hh:mm a").toFormatter(Locale.US);
LocalTime localStartTime = LocalTime.parse(startTime, formatterTime1);
Comments