为什么我得到不可解析的日期异常?

问题描述:

我无法使用SimpleDateFormat解析日期。我曾尝试这样的代码:为什么我得到不可解析的日期异常?

SimpleDateFormat fechas = new SimpleDateFormat("dd/MM/yyyy hh:mm"); 

if (data[i].length() > 1) { 
    Date f = (Date) fechas.parse(data[i]); 
    System.out.println(i + " " + f); 
} 

我收到以下错误:

Exception in thread "main" java.text.ParseException: Unparseable date: "01/06/2015 8:20 

我用下面的代码再有同样的问题:

SimpleDateFormat fech = new SimpleDateFormat(" yyyy/MM/dd HH:mm:ss"); 
Date date = (Date) fech.parse(data[i]); 
System.out.println(date); 

哪给出错误

Exception in thread "main" java.text.ParseException: Unparseable date: "00015/06/01 08:20:15" 

我该如何解决这个问题?

+5

您的日期字符串不匹配模式,就像错误消息告诉你。 – Keppil

+2

只是一个猜测,但...“01/06/2015”不包含“hh:mm”部分。第二件事情有:a)中间有两个空格,b)一年的“00015”,这个不是正确的。 –

+0

首先是“00015/06/01 08:20:15” 和另一个 “01/06/2015 8:20:10” –

使用SimpleDateFormat时,日期格式必须与完全匹配。在你的例子中,你包含日期,但是在你的日期格式中,你也指定了小时和分钟。如果你的数据有这个文本,它就会起作用。例如,使用您的第一个例子:

import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.HashMap; 
import java.util.Map; 

public class DateDemo { 
    public static void main(String args[]) throws Exception { 
    String yourData = "01/06/2015"; 
    String matchingData = "01/06/2015 13:00"; 
    SimpleDateFormat fechas = new SimpleDateFormat("dd/MM/yyyy hh:mm"); 

    Date matchingDate = fechas.parse(matchingData); 
    System.out.println("String: \"" + matchingData + "\" parses to " + matchingDate); 
    Date yourDate = fechas.parse(yourData); 
    System.out.println("String: \"" + yourData + "\" parses to " + yourDate); 
    } 
} 

此输出:

String: "01/06/2015 13:00" parses to Mon Jun 01 13:00:00 CDT 2015 
Exception in thread "main" java.text.ParseException: Unparseable date: "01/06/2015" 
     at java.text.DateFormat.parse(DateFormat.java:366) 
     at Demo.main(Demo.java:14) 

在你的日期String以及在SimpleDateFormat()模式应符合: -

SimpleDateFormat("dd/MM/yyyy hh:mm")将与01/06/2015 2:24

工作

AND

SimpleDateFormat("yyyy/MM/dd HH:mm:ss")2015/06/01 08:20:15

有关完整列表的工作,请参阅官方文档甲骨文here

import java.text.DateFormat; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

public class Test { 
    public static void main(String[] args) { 
     String dateText = "18/07/2015 05:30";   
     DateFormat fechas = new SimpleDateFormat("dd/MM/yyyy hh:mm"); 
     try { 
      Date parse = fechas.parse(dateText); 
      System.out.println("Date : " + fechas.format(parse)); 
     } catch (ParseException ex) { 
      Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    }  
} 

我做这样的源代码

+0

我还有同样的问题 –