我只是想在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。


当前回答

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

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

其他回答

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

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

试试这个:

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

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

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

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

如果您只是想采用一种格式(无论它是否有时间),并希望解析为LocalDateTime,您可以执行以下操作。

LocalDateTime parseDateTime(String dateTime, DateTimeFormatter fmt) {
  return fmt.parse(dateTime, t -> {
    LocalDate date = t.query(TemporalQueries.localDate());
    LocalTime time = t.query(TemporalQueries.localTime());
    return LocalDateTime.of(date, time != null ? time : LocalTime.MIDNIGHT);
  });
}

我需要这个,因为我要将日期/时间模式作为自定义Spark UDF的参数。

我遇到这个问题是因为我的输入字符串中没有年份:

输入字符串:周二,6月8日10:00 PM 格式化程序:DateTimeFormatter。ofPattern("EEEE, mm d 'at' h:mm a", Locale.US);

我知道年份,所以我只是把它附加到:

输入字符串:2021年6月8日星期二下午6:30 格式化程序:DateTimeFormatter。ofPattern("EEEE, mm d 'at' h:mm a uuuu", Locale.US);