-1
我想使用SimpleDateFormat格式化日期的字符串数组。它会正确格式化第一个条目,但声称第二个条目是不可解析的,即使它们是相同的。我无法弄清楚我在这里做错了什么,有什么提示?如何使用SimpleDateFormat格式化字符串数组
String dates = "";
String test = "MM/dd/yyyy";
String end = "MMMMMMMMM d, yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(test);
//Match the pattern of 1 or more digits, a backslash, one or more digits,
//a backslash, and then four digits
Pattern pattern = Pattern.compile("\\d+/\\d+/\\d\\d\\d\\d");
Matcher matcher = pattern.matcher(input);
//While there are matches, concatenate the match to the string dates,
//with a semicolon separating each match
while (matcher.find())
{
String a = matcher.group(0).toString();
dates += ";" + a;
}
//Split the string on semicolons
String[] inputString = dates.split(";");
for (int i=1; i<inputString.length; i++)
{
System.out.println(inputString[i]);
}
//Change all dates of format MM/dd/yyyy into Month date, year and
//force them into uppercase
for (int i=1; i<inputString.length; i++)
{
String old = inputString[i];
Date a = sdf.parse(old);
sdf.applyPattern(end);
String notOld = sdf.format(a);
inputString[i] = notOld;
inputString[i] = inputString[i].toUpperCase();
System.out.println(inputString[i]);
}
这里是输出:
12/6/1852
12/6/1954
DECEMBER 6, 1852
Exception in thread "main" java.text.ParseException: Unparseable date: "12/6/1954"
at java.text.DateFormat.parse(Unknown Source)
at Info.fixer(Info.java:132)
at Info.main(Info.java:35)
'这个例子中的变量输入是什么? –
对于此片段,文本文件仅保留: “12/6/1852 12/6/1954” 两行。字符串还有很多,因为它是一个很长的文本文件,我在这里提取日期,但是这些文件正在文件的顶部进行测试,所以它永远不会超过它们。 –
当你调用'applyPattern(end)',你改变'sdf'来格式化'MMMMMMMMM d,yyyy'。在下一次迭代中,您尝试使用该格式解析'12/6/1954',并且糟糕!这是行不通的。 – Andreas