2013-01-14 29 views
-1

我需要驗證一個字符串,看它是否代表ISO格式的日期,如果它不需要拋出用戶定義的異常。在java中的日期驗證

我有這行代碼,

DateTimeFormatter formatter = ISODateTimeFormat.date(); 

如何使用這個格式來驗證字符串?

+0

爲什麼拋出一個用戶定義的異常?有一個DateFormatException內置到現有的日期格式庫。您也可以拋出另一個運行時異常,如IllegalArgumentException。你是否期望從異常中恢復? – Foo

+0

爲什麼不使用SimpleDateFormat:http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html? – amphibient

+0

@Foo因爲特定於應用程序的異常通常比低級異常更有用。 –

回答

1

試圖用formatter.parseDateTime()方法解析它。

當字符串不是有效日期時,它將拋出IllegalArgumentException。當你想拋出自己的異常時,只需抓住它並拋出另一個異常。

0

你可以嘗試用formatter您已經瞭解瞭解析,抓IllegalArgumentException,並拋出而不是用戶定義的異常:

try { 
    formatter.parseMillis(stringBeingValidated); // You can use another parseXYZ method here 
} catch (IllegalArgumentException iae) { 
    throw new CustomException(iae.getMessage()); // The getMessage() call is only an example. 
}