2016-09-07 126 views
-2

我尝试将字符串转换为java上的日期。我阅读并尝试从这个网站"Java Date and Calendar examples"的例子,但我仍然无法编译和运行它。Java:错误解析日期字符串到日期对象

这是我的代码。

package javaapplication5; 

import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.Date; 
import java.util.Locale; 

public class JavaApplication5 { 

    public static void main(String[] args) { 
     SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); 
     String dateInString = "31-08-1982 10:20:56"; 
     Date date = sdf.parse(dateInString); 
     System.out.println(date); 
    } 

} 

我得到这个错误。

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.text.ParseException; must be caught or declared to be thrown 

我错过或做错了什么?谢谢你的帮助。

+0

是错误是如此的清晰,无论你需要将'sdf.parse()'放在try catch或use throws子句中。 –

回答

1

的问题是,java.text.ParseExceptionchecked exception

checked异常是一种例外,那必须是捕获或在其被抛出

所以方法声明中...你可能会在throws列表声明它

public static void main(String[] args) throws ParseException { 
    /* ... */ 
} 

还是应该妥善处理这

public static void main(String[] args) { 
    try { 
     Date date = sdf.parse(dateInString); 
    } catch (ParseException e) { 
     // do proper thing here like try another 
     // format or log/rethrow/wrap exception 
    } 
} 
+0

感谢您包括这两种方式可以完成。因为它揭示了编译错误的原因,所以你很快就会解释检查的异常。 – byxor

+1

@BrandonIbbotson在此向您致谢:) – vsminkov

+1

@BrandonIbbotson标记为重复的会更好,但是谁会对一些容易养殖的声誉说“不”,对吧? :P – Tom

0

只需在try catch块中添加代码即可。

try { 
//parse code 
} 
catch (ParseException e) { 
//handling exceptions 
} 
0

尽量把所有的代码在一个try/catch块

try{ 
    // your code here. 
}catch(Exception e){ 
    e.printStackTrace(); 
} 
+2

这会起作用,但它会捕获所有异常,这不是一个好主意。 – byxor

+0

是的,如果你想捕捉解析异常,你可以用catch子句中的“ParseException”替换“Exception”。 –

0

添加try-catch块这样的:

try 
{ 
    //...Code.... Mainly below: 
    Date date = sdf.parse(dateInString); 
} catch (ParseException e) 
    //Or any superclass, such as RuntimeException, 
    //although use superclass ONLY to be generic, not otherwise, such as 
    //if you want to handle all exceptions the same way. 
{ 
    //...Handler Code... 
} 
+0

编辑答案@Tom –

+1

@Tom再次编辑 –

0
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); 
      String dateInString = "31-08-1982 10:20:56"; 
      Date date = null; 
      try { 
       date = sdf.parse(dateInString); 
      } catch (ParseException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      System.out.println(date); 
+0

解释你的答案 – Tom