【问题标题】:Java LocalDateTime Text could not be parsed at index 0 exceptionJava LocalDateTime 文本无法在索引 0 异常处解析
【发布时间】:2020-08-15 17:32:17
【问题描述】:

尝试将字符串格式的日期转换为 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:无法在索引 0 处解析文本“01/03/2020 15:13”

这种格式不支持转换吗?

【问题讨论】:

  • "这个格式不支持转换吗?"谁告诉你的? LocalDateTime.parse(CharSequence) 在内部使用 DateTimeFormatter.ISO_LOCAL_DATE_TIME。你的意思是写parse(caseStartDate, dateFormat)?
  • 你想得到什么?为什么?

标签: java localdatetime


【解决方案1】:

您需要在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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2020-06-25
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多