如何使用SimpleDateFormat格式化字符串数组

时间:2016-04-30 05:03:00

标签: java simpledateformat

我尝试使用SimpleDateFormat格式化日期的String数组。它将正确格式化第一个条目,但声称第二个条目是不可解析的,即使它们是相同的。我无法弄清楚我在这里做错了什么提示?

    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)

1 个答案:

答案 0 :(得分:0)

安德烈亚斯&#39;评论有帮助。我不知道simpledateformat使用applyPattern()设置格式,因此它为后续值使用了不同的模式。这个改变到底部循环修复了它:

for (int i=1; i<inputString.length; i++)
{
    sdf1.applyPattern(dmy);
    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]);
}