【问题标题】:java.text.ParseException: Unparseable date: "Augu 16, 1979" [duplicate]java.text.ParseException:无法解析的日期:“1979 年 8 月 16 日”[重复]
【发布时间】:2020-04-19 19:57:01
【问题描述】:

如果我尝试 replace("st", "") 所以它发生 URLjava.text.ParseException: Unparseable date: "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);  

【问题讨论】:

标签: java date format simpledateformat date-formatting


【解决方案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

【讨论】:

  • 就我而言,我不会在解析之前对原始字符串进行任何替换。无论我们谈论的是现代的DateTimeFormatter 还是臭名昭著和过时的SimpleDateFormat,两者都能够解析字符串,因为它使用可选部分和文字文本,如链接的原始问题的一些答案所示。
【解决方案2】:

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

【讨论】:

  • 这听起来很简单,但会随着您的需要而增长,如第 1、第 2、第 3、第 4、...、第 11、第 12、... 直到第 31 次。
【解决方案3】:

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

【讨论】:

  • 这似乎与提问者所遇到的问题无关(有关详细信息,请参阅其他答案;我承认问题本身并没有很好地解释它)。
猜你喜欢
  • 2022-10-14
  • 2015-02-16
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
  • 1970-01-01
  • 2021-07-05
  • 2013-05-28
  • 1970-01-01
相关资源
最近更新 更多