2010-11-06 102 views
0

我試圖做一些非常簡單的事情 - 取當前的日期和時間,並以期望的格式解析它。帶模式的SimpleDateFormat導致錯誤無法解析日期

private final String datePattern = "yyyy:DDD"; 
private final String timePattern = "hh:mm:ss"; 

public void setDateAndTime(){ 

    // Default constructor initializes to current date/time 
    Date currentDateAndTime = new Date(); 

    SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern); 
    SimpleDateFormat timeFormatter = new SimpleDateFormat(timePattern); 

    try { 

    this.date = dateFormatter.parse(currentDateAndTime.toString()); 
    this.time = timeFormatter.parse(currentDateAndTime.toString()); 

    } catch (ParseException e){ 
    System.out.println("Internal error - unable to parse date/time"); 
    System.exit(1); 
    } 

} 

這將導致一個例外:

無法解析的日期: 「星期六2006年11月11時04分22秒EDT 2010」

這是一個完全有效的日期字符串,我用來初始化SimpleDateFormat的模式似乎是正確的。

如何避免這個錯誤,以及如何初始化SimpleDateFormat

+0

無關的問題,你不能格式化日期對象:這是錯誤的地方打電話'系統。出口()'。你不想只從方法中拋出異常或返回嗎? – BalusC 2010-11-06 15:43:21

回答

4
  • 解析String
  • 格式化Date

得到一個String得到一個Date你需要後者 - 所以使用formatter.format(currentDateAndTime)

你得到例外,因爲你改變了你的DateStringtoString()您稍後嘗試解析,但不符合您指定的格式。

0

你的代碼應該是

SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern); SimpleDateFormat timeFormatter = new SimpleDateFormat(timePattern); System.out.println(dateFormatter.format(currentDateAndTime));

簡單地說,除非輸出是一個字符串

相關問題