1

Here is a sample input from the user:

Wed 15:00

I want to parse this into an object so I'm using a LocalDateTime 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?

Richard
  • 5,840
  • 36
  • 123
  • 208

1 Answers1

4

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!

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • then how do I handle parsing both `wed 1:00` and `wed 11:00`? – Richard Nov 03 '16 at 01:56
  • 1
    The code you posted is not valid to begin with. What _type_ exactly do you want to return? – Óscar López Nov 03 '16 at 01:58
  • I want to return a `LocalDateTime` object but I'm not sure that's the proper object to use. And I tried the above pattern and still got the same error – Richard Nov 03 '16 at 02:02
  • 1
    Notice that the string must be `Wed 15:00`, with a capital `W`. And I'm not quite sure _why_ you want to return a `LocalDateTime`... – Óscar López Nov 03 '16 at 02:04
  • ok `DATE_TIME_FORMATTER.parse(elem)` works but `LocalDateTime.from(DATE_TIME_FORMATTER.parse(elem))` fails because `Unable to obtain LocalDateTime from TemporalAccessor: {DayOfWeek=3},ISO resolved to 15:00 of type java.time.format.Parsed` – Richard Nov 03 '16 at 02:07
  • 3
    You'll have to specify more than just the day of the week and time to parse a `LocalDateTime` object. I really, really think you have to go back to the drawing board and rethink what you're trying to accomplish, and whether `LocalDateTime` is the best data type for it. – Óscar López Nov 03 '16 at 02:21