我只是想在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的答案..:我有同样的问题,即使使用LocalDate而不是LocalDateTime。问题是,我已经创建了我的DateTimeFormatter使用. withresolverstyle (ResolverStyle.STRICT);,所以我必须使用日期模式uuuuMMdd而不是yyyyMMdd(即。“year”而不是“year-of-era”)!

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

(这个解决方案最初是对retrography的答案的评论,但我被鼓励将其作为一个独立的答案发布,因为它显然对许多人都很有效。)

其他回答

这是一个非常不清楚且毫无帮助的错误消息。经过多次尝试和错误后,我发现如果您不尝试解析时间,LocalDateTime将给出上述错误。通过使用LocalDate,它可以正常工作而不会出错。

这没有很好的记录,相关的异常也没有什么帮助。

试试这个:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy"); 
LocalDate fromLocalDate = LocalDate.parse(fromdstrong textate, dateTimeFormatter);

你可以添加任何你想要的格式。这对我很有用!

您不需要定义DateTimeFormatter

您不需要定义DateTimeFormatter来解析给定的日期字符串。您可以使用OOTB(开箱即用)、DateTimeFormatter。BASIC_ISO_DATE解析它。

演示:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.parse("20140218", DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println(date);

        // In case you need an instance of LocalDateTime
        LocalDateTime ldt = date.atTime(LocalTime.MIN);
        System.out.println(ldt);
    }
}

输出:

2014-02-18
2014-02-18T00:00

在线演示

了解更多关于现代日期时间API*从Trail: Date Time。


*如果你正在为一个Android项目工作,而你的Android API级别仍然不兼容Java-8,检查Java 8+ API通过desugaring可用。注意,Android 8.0 Oreo已经提供了对java.time的支持。检查这个答案和这个答案,学习如何使用java。使用JDBC的时间API。

事实证明,Java不接受裸Date值作为DateTime。使用LocalDate而不是LocalDateTime解决了这个问题:

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

如果你真的需要将日期转换为LocalDateTime对象,你可以使用LocalDate.atStartOfDay()。这将给你一个指定日期的LocalDateTime对象,将小时、分钟和秒字段设置为0:

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