如果我尝试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);
问题在于,replace("st", "")
也删除了st
的August
结尾,导致在错误消息中看到输入字符串。
要处理此问题,您需要确保st
后缀紧靠数字,因此它是日值的一部分。您还需要处理所有1st
,2nd
,3rd
和4th
。
这意味着您应该使用正则表达式,如下所示:
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
MMMM
格式应提供完整的月份名称。尝试使用Locale.US
。
您还将在“八月”中替换“ st”。使用replace("1st", "1")
。
而不是匹配st
,而是匹配(\d*)st
,然后将其替换为\1
。
有关更多信息,请参考Pattern
和String::replace
的javadocs。
如果对1st
执行此操作,则还应该考虑2nd
,3rd
,4th
等的情况。
((请注意,如果使用字符串文字表示这些模式,则需要额外的\
来转义\
元字符。)