java.text.ParseException:无法解析的日期:“ 1979年8月16日” [重复]

问题描述 投票:-5回答:3

如果我尝试replace(“ st”,“”)以便出现URLjava.text.ParseException:无法解析的日期:“ 1979年8月16日”

请帮助....

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
3个回答
1
投票

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

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

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

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

Test

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

0
投票

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


0
投票

您还将在“八月”中替换“ st”。使用replace("1st", "1")


0
投票

而不是匹配st,而是匹配(\d*)st,然后将其替换为\1

有关更多信息,请参考PatternString::replace的javadocs。

如果对1st执行此操作,则还应该考虑2nd3rd4th等的情况。

((请注意,如果使用字符串文字表示这些模式,则需要额外的\来转义\元字符。)

© www.soinside.com 2019 - 2024. All rights reserved.