parsingLocalDateTime(Java 8)时无法从TemporalAccessor获取LocalDateTime

我只是试图将datestring转换为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

事实certificate,Java不接受作为DateTime的date值。 使用LocalDate而不是LocalDateTime解决了这个问题:

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

如果您确实需要将date转换为LocalDateTime对象,则可以使用LocalDate.atStartOfDay()。 这将在给定的date为您提供一个LocalDateTime对象,将小时,分钟和秒字段设置为0:

 final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); LocalDateTime time = LocalDateTime.from(LocalDate.parse("20140218", formatter).atStartOfDay()); 

这是一个非常不清楚和无益的错误信息。 经过大量的试验和错误,我发现LocalDateTime会给出上述错误,如果你不试图parsing一个时间。 通过使用LocalDate而不是错误。

这是logging不好,相关的例外是非常无益的。

对于什么是值得的,如果有人应该再读一遍这个话题(像我)正确的答案是在DateTimeFormatter定义,例如:

 private static DateTimeFormatter DATE_FORMAT = new DateTimeFormatterBuilder().appendPattern("dd/MM/yyyy[ [HH][:mm][:ss][.SSS]]") .parseDefaulting(ChronoField.HOUR_OF_DAY, 0) .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0) .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0) .toFormatter(); 

一个应该设置可选字段,如果他们将出现。 其余的代码应该完全一样。

扩大retrography的答案 ..:即使使用LocalDate而不是LocalDateTime时,我也有这个相同的问题。 问题是我用.withResolverStyle(ResolverStyle.STRICT);创build了我的DateTimeFormatter .withResolverStyle(ResolverStyle.STRICT); ,所以我不得不使用date模式uuuuMMdd而不是yyyyMMdd (即“年”而不是“年代”)!

 DateTimeFormatter formatter = new DateTimeFormatterBuilder() .parseStrict() .appendPattern("uuuuMMdd") .toFormatter() .withResolverStyle(ResolverStyle.STRICT); LocalDate dt = LocalDate.parse("20140218", formatter); 

(这个解决scheme最初是对retrography的答案的一个评论,但我被鼓励把它作为一个独立的答案发布,因为它对很多人来说显然工作得很好。)