我想将日期时间字符串解析为LocalDateTime。输入格式不能包含小时,分钟等字段。例如,可以是“ yyyy M d”。在这种模式下,您可以将字符串解析为LocalDate,但不能解析为LocalDateTime。我要创建LocalDateTime。
有一种使用DateTimeFormatterBuilder做到这一点的方法,如下所示。
// this code works. But I don't want to use DateTimeFormatterBuilder
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyyy")
.appendLiteral('-')
.appendValue(MONTH_OF_YEAR)
.appendLiteral('-')
.appendValue(DAY_OF_MONTH)
.parseDefaulting(HOUR_OF_DAY, 12)
.parseDefaulting(MINUTE_OF_HOUR, 13)
.parseDefaulting(SECOND_OF_MINUTE, 14)
.toFormatter();
System.out.println(LocalDateTime.parse("2015-09-05", formatter));
但是我想使用DateTimeFormatter.ofPattern()代替DateTimeFormatterBuilder。但是我不知道如何使以下代码起作用:
// this code doesn't work.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
System.out.println(LocalDateTime.parse("2015-09-05", formatter));
它引发异常
Exception in thread "main" java.time.format.DateTimeParseException: Text '2015-09-05' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2015-09-05 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
...