一尘不染

解析LocalDateTime(Java 8)时,无法从TemporalAccessor获取LocalDateTime

java

我只是想将Java 8中的日期字符串转换为DateTime对象。运行以下行时:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime dt = LocalDateTime.parse("20140218", formatter);

我收到以下错误:

Exception in thread "main" java.time.format.DateTimeParseException: 
Text '20140218' could not be parsed: 
Unable to obtain LocalDateTime from TemporalAccessor: 
{},ISO resolved to 2014-02-18 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)

语法与此处建议的语法相同,但有例外。我正在使用JDK-8u25。


阅读 701

收藏
2020-03-22

共1个答案

一尘不染

事实证明Java不接受裸露的Date值作为DateTime。使用LocalDate代替LocalDateTime解决了此问题:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dt = LocalDate.parse("20140218", formatter);
2020-03-22