将字符串更改为日期

时间:2016-07-05 06:56:56

标签: java string date

我尝试更改字符串,如下所示:4th of July 2016

我试图运行的代码是:

        Date d = null;
        String[] formats = {"d'st of' MMMMM yyyy","d'nd of' MMMMM yyyy","d'rd of' MMMMM yyyy","d'th of' MMMMM yyyy"};
        for (String format : formats) {
            try {
                d = new SimpleDateFormat(format).parse(date);
            }
            catch (Exception e){
                System.out.println("Error in ConvertStringToDate s" + e);
            } 
        }
System.out.print(d.toString());

我从控制台收到的错误:

Error in ConvertStringToDate sjava.text.ParseException: Unparseable date: "4th of July 2016"
Error in ConvertStringToDate sjava.text.ParseException: Unparseable date: "4th of July 2016"
Error in ConvertStringToDate sjava.text.ParseException: Unparseable date: "4th of July 2016"
Error in ConvertStringToDate sjava.text.ParseException: Unparseable date: "4th of July 2016"
Exception in thread "main" java.lang.NullPointerException
    at MatchData.CollectMatch(MatchData.java:113)
    at GetData.main(GetData.java:13)

感谢任何试图提供帮助的人:)

1 个答案:

答案 0 :(得分:0)

使用st of删除所有nd ofrd ofth ofString.replace,然后使用d MMMMM yyyy解析日期。< / p>

new SimpleDateFormat(format).parse(
    date.replace("st of", "")
        .replace("nd of", "")
        .replace("rd of", "")
        .replace("th of", "")
);