我只是想在 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
。
原文由 retrography 发布,翻译遵循 CC BY-SA 4.0 许可协议
事实证明,Java 不接受裸日期值作为 DateTime。使用 LocalDate 而不是 LocalDateTime 解决了这个问题: