Richard Richard - 1 year ago 68
Java Question

Java 8 Parse Day of the Week and Time

Here is a sample input from the user:

Wed 15:00

I want to parse this into an object so I'm using a
object. Here's my code:

String elem = "wed 15:00";
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(
"E H:mm"
+ "E HH:mm");
return LocalDateTime.from(DATE_TIME_FORMATTER.parse(elem));

But I'm getting the error:

java.time.format.DateTimeParseException: Text 'wed 15:00' could not be parsed at index 0

What exactly is the error here?

Answer Source

This is not a valid pattern:

"E H:mm" + "E HH:mm"

Try this instead:

String elem = "Wed 15:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E H:mm");
return LocalDateTime.from(LocalDate.parse(elem, formatter));

Also notice that you'll have to specify more than just the day of the week and time to parse a LocalDateTime object, it stands to reason: we don't know what Wednesday are we talking about!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download