Chenya Zhang Chenya Zhang - 1 year ago 122
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".


timeFormat : 'hh:mm a',
interval : 30,
maxTime : '11:00 pm',
startTime : '08:00 am',
dynamic : false,
dropdown : true,
scrollbar : true


<div class="form-group">
class="col-md-3 control-label">Start
<div class="col-md-7">
<input type="text"

In Java:

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


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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download