2011-12-19 37 views
0

當用戶輸入錯誤格式的日期時,出現空指針異常。將字符串轉換爲日期 - 日期驗證

方法將字符串轉換爲日期

Date stringToDate(String dateString) { 

     Date returnDate = null; 
     if (dateString!= null && dateString.length() > 0 && isValidDate(dateString)) { 
      returnDate = dateFormat.parse(dateStr); 
     } 
     return returnDate; 
    } 

boolean isValidDate(String date) { 
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); 
    Pattern datePattern = Pattern.compile("[0-9]{2}/[0-9]{2}/[0-9]{4}"); 
    Matcher datePatternMatch = datePattern.matcher(date); 

    boolean datePatternMatchfound = datePatternMatch.matches(); 

    if(date==null){ 
     return false; 
    } else if(date!=null && date.length()>0){  
     if(datePatternMatchfound){ 
      sdf.setLenient(false); 
      sdf.parse(date.trim()); 
     } 
     return true; 
    } else { 
     return false; 
    } 
} 

我只是好奇,想知道....

1)應該是什麼日期有效模式?

2)如果用戶輸入錯誤日期stringToDate方法肯定會失敗並拋出空指針異常。如何避免這種情況?

任何幫助真的不勝感激。

+0

你使用JSF。如果你確實將它用於JSF輸入字段,那麼你正在接近完全錯誤。 – BalusC

回答

2

你假設的SimpleDateFormat(MM-DD-yyyyas默認模式,用戶將輸入,要麼你應該確保你的用戶只能在SimpleDateFormat的進入,或者你應該在isValidDate()接受

0
  1. 有效的模式格式取決於系統的國家設置。

  2. 您應該將isValidDate()方法的內容放在try-catch塊中以避免發生異常。日期表示的

1

正確的格式完全取決於你的應用程序和用戶的語言環境。但是,您可以將輸入格式限制爲某種格式,然後使用它來解析和格式化日期輸入。

您可以捕獲parse方法拋出的ParseException,並處理catch子句中的無效情況。

例如你的代碼可以簡化爲以下幾點:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); 

Date stringToDate(String dateString) { 
    try { 
    Date returnDate = sdf.parse(dateString); 
    // do something with returnDate, if necessary 
    return returnDate; 
    } catch(ParseException e) { 
    // Date is not valid, handle invalid cases here.. 
    return null; // Not a good practice, you probably would throw an Exception 
    } 
} 

而且你可以使用相同的格式化程序通過調用sdf.format(someDate)方法獲得String表示,以顯示在用戶界面中你的價值觀。

+0

即使我刪除了模式匹配條件,並且用戶輸入了一些隨機數值,它會給出解析問題。日期格式在「MM/dd/yyyy」中定義 –

+0

我將回答改爲使用斜槓而不是破折號。 – melihcelik

1
變化。

一件事是,你需要更多的防守在您的驗證方法

在你的代碼所顯示的,你這樣做:。

Matcher datePatternMatch = datePattern.matcher(date); 

您檢查之前的日期字符串是否爲空Pattern.matcher(null)結果在NullPoint中erException。

因此,您需要在if (date != null)條件塊內移動此代碼。

除此之外,在使用DateFormat進行驗證之前,我沒有看到使用正則表達式驗證日期String的好處。正則表達式驗證不會給你任何額外的好處。

0

使用Simple date format類,我們可以驗證,如果string是日期或不是。您需要確保將setLenient(false)設置爲simple date format對象。

如果沒有設置你是按四捨五入values.For例如與發行結束,一個寬鬆的GregorianCalendar解釋MONTH == JANUARY,DAY_OF_MONTH == 32月1

示例代碼:

http://www.vijayakumarg.co.in/2014/04/how-to-validate-date-string-in-java.html根據您的問題,歷史

public static boolean validateJavaDate(String strDate) 
{ 

    /* 
    * Set preferred date format, 
    * For example MM-dd-yyyy, MM.dd.yyyy,dd.MM.yyyy etc.*/ 
    SimpleDateFormat sdfrmt = new SimpleDateFormat("MM/dd/yyyy"); 
    sdfrmt.setLenient(false); 
    /* Create Date object */ 
    Date javaDate = null; 
    /* parse the string into date form */ 
    try 
    { 
     javaDate = sdfrmt.parse(strDate); 
     System.out.println("Date after validation: " + javaDate); 
    } 
    /* Date format is invalid */ 
    catch (ParseException e) 
    { 
     System.out.println("The date you provided is in an " +"invalid date format."); 
     return false; 
    } 
    /* Return 'true' - since date is in valid format */ 
    return true; 

}