问题
我只是想在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)
语法与已建议的here相同,但我遇到了一个例外。我正在使用JDK-8u25。
#1 热门回答(101 赞)
事实证明,Java不接受Date Date值作为DateTime。使用LocalDate而不是LocalDateTime解决了这个问题:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dt = LocalDate.parse("20140218", formatter);
#2 热门回答(39 赞)
如果你确实需要将日期转换为LocalDateTime对象,则可以使用LocalDate.atStartOfDay()。这将在指定日期为你提供LocalDateTime对象,将小时,分钟和秒字段设置为0:
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime time = LocalDate.parse("20140218", formatter).atStartOfDay();
#3 热门回答(26 赞)
这是一个非常不清楚且无用的错误消息。经过多次试验和错误后,我发现如果你不试图解析时间,LocalDateTime会给出上述错误。通过使用LocalDate,它可以正常工作而不会出错。
这个记录很少,相关的例外情况非常无益。