在Java中将String转换为LocalDateTime

时间:2018-05-14 14:55:09

标签: java parsing formatter localdate

我试图将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)

谢谢!

1 个答案:

答案 0 :(得分:2)

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

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