java.text.ParseException:无法解析的日期:"Augu 16, 1979"

java.text.ParseException: Unparseable date: "Augu 16, 1979"

如果我尝试替换 ("st", "") 所以它会发生 URLjava.text.ParseException: 无法解析的日期: "Augu 16, 1979"

请帮忙....

DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
    DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
    Date date = originalFormat.parse("August 21st, 2012");
    String formattedDate = targetFormat.format(date);  

MMMM 格式应给出完整的月份名称。尝试使用 Locale.US .

您也在 "August" 中替换 "st"。使用 replace("1st", "1").

问题是 replace("st", "") 还删除了 Augustst 结尾,导致在错误消息中看到输入字符串。

要处理此问题,您需要确保 st 后缀紧跟在数字之后,因此它是日期值的一部分。您还需要处理所有 1st2nd3rd4th.

这意味着您应该使用正则表达式,如下所示:

replaceFirst("(?<=\d)(?:st|nd|rd|th)", "")

测试

public static void main(String[] args) throws Exception {
    test("August 20th, 2012");
    test("August 21st, 2012");
    test("August 22nd, 2012");
    test("August 23rd, 2012");
    test("August 24th, 2012");
}
static void test(String input) throws ParseException {
    String modified = input.replaceFirst("(?<=\d)(?:st|nd|rd|th)", "");

    DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
    DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
    Date date = originalFormat.parse(modified);
    System.out.println(targetFormat.format(date));
}

输出

20120820
20120821
20120822
20120823
20120824