Java 无法在索引 0 处解析 LocalDateTime 文本异常

Java LocalDateTime Text could not be parsed at index 0 exception

正在尝试将字符串格式的日期转换为 Java LocalDateTime。

private DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
private String caseStartDate = dateFormat.format(LocalDateTime.now());

LocalDateTime localdatetime = LocalDateTime.parse(caseStartDate);

但最终出现了这个异常:

java.time.format.DateTimeParseException: Text '01/03/2020 15:13' could not be parsed at index 0

这种格式不支持转换吗?

您需要在 LocalDateTime::parse 中使用您的格式,如下所示:

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

class Main {
    public static void main(String[] args) {
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
        String caseStartDate = dateFormat.format(LocalDateTime.now());
        System.out.println(caseStartDate);
        LocalDateTime localdatetime = LocalDateTime.parse(caseStartDate, dateFormat);
        System.out.println(localdatetime);
    }
}

输出:

01/05/2020 09:13
2020-05-01T09:13

另外,看看 LocalDateTimetoString() 方法是如何被覆盖的:

@Override
public String toString() {
    return date.toString() + 'T' + time.toString();
}