最近開發公司的項目,一直找不到合適的正則表達式能夠判斷一個字符串是否能夠轉成日期,今天發現能夠採用SimpleDateFormat類的parse方法進行判斷,若是轉換不成功,就會出現異常,html
具體代碼以下:java
1 public static boolean isValidDate(String str) { 2 boolean convertSuccess=true; 3 // 指定日期格式爲四位年/兩位月份/兩位日期,注意yyyy/MM/dd區分大小寫; 4 SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm"); 5 try { 6 // 設置lenient爲false. 不然SimpleDateFormat會比較寬鬆地驗證日期,好比2007/02/29會被接受,並轉換成2007/03/01 7 format.setLenient(false); 8 format.parse(str); 9 } catch (ParseException e) { 10 // e.printStackTrace(); 11 // 若是throw java.text.ParseException或者NullPointerException,就說明格式不對 12 convertSuccess=false; 13 } 14 return convertSuccess; 15 }