无法在索引 0 处解析文本 '1/1/2020 12:12:12' 1/1/2020 12:12:12 MM/dd/yyyy HH:mm:ss

Text '1/1/2020 12:12:12' could not be parsed at index 0 1/1/2020 12:12:12 MM/dd/yyyy HH:mm:ss

下面的代码抛出错误,不知道为什么 1 不被接受为 01 并抛出异常

failure Text '1/1/2020 12:12:12' could not be parsed at index 0
1/1/2020 12:12:12 MM/dd/yyyy HH:mm:ss
try {
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss", Locale.US)
        .withResolverStyle(ResolverStyle.STRICT);
    System.out.println("success " + dateFormatter.parse(1/1/2020 12:12:12));
} catch (Exception e) {
    System.out.println("failure " + e.getMessage());
}

DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss", Locale.US) 接受月和日 恰好 两个位置的日期。对于您的输入,需要 DateTimeFormatter.ofPattern("M/d/yyyy HH:mm:ss", Locale.US), ResolverStyle.STRICT)