2013-10-29 33 views
0

您好我正在使用SimpleDateFormat解析和比較字符串中的兩個日期。這裏是我的代碼SimpleDateFormat異常

private static int compareDates(String lineFromFile, String givenDate) throws ParseException, IllegalArgumentException 
    { 
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); 
    Date dateFromfile = sdf.parse(tmp); 
    Date givenDateTime = sdf.parse(givenDate); 
    if (dateFromfile.equals(givenDateTime)) 
    { 
     return 0; 
    } 
    if (dateFromfile.before(givenDateTime)) 
    { 
     return 1; 
    } 

     return -1; 
    } 

這裏是一個主要方法

public static void main(String[] args) { 
    try 
    { 
     int result = compareDates("00:45:44", "09:35:56"); 
     System.out.println(line); 
    } 
    catch (ParseException e) 

    { 
     e.printStackTrace(); 
     System.out.println("ERROR"); 
    } 

} 

這正常工作,當我路過有效參數,但!希望在傳遞例如「28:40:04」時出現異常,現在我只有在傳遞包含字母的參數字符串時纔有例外。

回答

3

您需要設置寬鬆,以false(默認行爲是寬鬆):

sdf.setLenient(false); 

What is the use of "lenient "?javadoc

指定日期/時間分析是否是寬鬆的。通過寬鬆的解析,解析器可以使用啓發式來解釋不精確匹配此對象格式的輸入。通過嚴格的解析,輸入必須匹配這個對象的格式。

+0

我想這一點,但它的結果是一樣的 –

+1

其實這是默認寬鬆,你需要將其設置爲false:sdf.setLenient(假); – lbalazscs

+0

謝謝,它有幫助! –