首页 > 解决方案 > java.time.format.DateTimeParseException:无法在索引 0 处解析文本“2020 年 6 月 4 日上午 8:58:15”

问题描述

我得到错误:

java.time.format.DateTimeParseException
无法在索引 0 处解析文本“2020 年 6 月 4 日上午 8:58:15”

String ajourTsAdjusted = "Jun 4 2020 8:58:15 AM";
DateTimeFormatter dt = DateTimeFormatter.ofPattern("MMM d yyyy h:mm:ss a");
LocalDateTime ajDate = LocalDateTime.parse(ajourTsAdjusted, dt);

有人可以看到我在这里没有做什么吗?

问候弗莱明

标签: java

解决方案


我假设您的系统语言不是英语。

做出此假设是因为您的错误语言说明(..) cannot be parsed at index 0,即日期的开头。图案。

在那里,您有一个月份名称的缩写,这些缩写因语言而异。在我的国家,Jun是英语中June的缩写,但巧合的是,它也是Juni的德语缩写,这使得这段代码可以在我的系统上运行。
如果DateTimeFormatter您不提供不同/特定的Locale.

为确保解析英文日期时间,Locale请提供DateTimeFormatter

public static void main(String[] args) {
    String ajourTsAdjusted = "Jun 4 2020 8:58:15 AM";
    DateTimeFormatter dt = DateTimeFormatter.ofPattern("MMM d yyyy h:mm:ss a",
                                                        Locale.ENGLISH);
    LocalDateTime ajDate = LocalDateTime.parse(ajourTsAdjusted, dt);
    System.out.println(ajDate);
}

这将像这样输出 ISO 格式的日期String时间:

2020-06-04T08:58:15

推荐阅读