轉自:http://www.cnblogs.com/xdp-gacl/p/3548307.html
最近開發公司的項目,一直找不到合適的正則表達式可以判斷一個字符串是否可以轉成日期,今天發現可以採用SimpleDateFormat類的parse方法進行判斷,如果轉換不成功,就會出現異常,
具體代碼如下:
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 }