Search code examples
javaparsingformatterlocaldate

converting String to LocalDateTime in Java


I'm trying to convert String to LocalDateTime object, but java is not letting me.

String date = in.nextLine().trim();
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);

output:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2018-03-03' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2018-03-03 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDateTime.parse(Unknown Source)

Thank you!


Solution

  • You are trying to parse a raw date to a LocalDateTime object which is not allowed.

    You need to parse it to a LocalDate object instead.