在 Java 中将 String 转换为 LocalDateTime

converting String to LocalDateTime in Java

我正在尝试将 String 转换为 LocalDateTime 对象,但 java 不允许。

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

输出:

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)

谢谢!

您正在尝试将原始日期解析为 LocalDateTime 对象,这是不允许的。

您需要将其解析为 LocalDate 对象。