转换为时间戳时无法解析日期

时间:2014-06-09 16:35:09

标签: java

任何人都可以请我清楚,这个例外意味着什么:

  

线程“main”中的异常java.text.ParseException:Unparseable date:“06.10.2013 00:00”。

在文件06.10.2013中找到了这样一个无法解析的日期?它一定是06/10/2013吗?当我在阅读文件时将String[]转换为Timestamp时,我明白了。但是我在03/10/2013和03.10.2013这样的文件中有两种格式,我必须使用它,而不是这样:

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");


                String[] temp = line.split(",");

                SimpleDateFormat dateFormat = new SimpleDateFormat(
                        "MM/dd/yyyy HH:mm" );


                java.util.Date parsedDate = dateFormat.parse(temp[0]);

                java.sql.Timestamp timestamp = new java.sql.Timestamp(
                        parsedDate.getTime());
                for (int i = 1; i < temp.length; i++) {

                o.setTimestamp(timestamp);

我在我的档案06.10.2013 15:00:00和06/10/2013 15:00:00

中默认两种格式

1 个答案:

答案 0 :(得分:1)

在天真地尝试使用您当前的String解析它之前,对SimpleDateFormat执行分析:

SimpleDateFormat dateFormat;
//check if the string to parse contains a dot
if (stringContainingTimestamp.contains(".")) {
    dateFormat = new SimpleDateFormat("MM.dd.yyyy HH:mm");
} else {
    dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
}
//rest of the code...

另一个选项可能是使用String#replace(char, char)斜杠替换点字符:

stringContainingTimestamp = stringContainingTimestamp.replace('.', '/');
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
//rest of the code...

选择权在你手中。

相关问题