Java檢查日期格式
如何檢查檢查日期是否為正確的格式?
解決方法
下麵的例子演示了如何使用String類的matches()方法檢查日期是否是在一個適當的格式。
public class Main { public static void main(String[] argv) { boolean isDate = false; String date1 = "8-05-1988"; String date2 = "08/04/1987" ; String datePattern = "\d{1,2}-\d{1,2}-\d{4}"; isDate = date1.matches(datePattern); System.out.println("Date :"+ date1+": matches with the this date Pattern:"+datePattern+"Ans:"+isDate); isDate = date2.matches(datePattern); System.out.println("Date :"+ date2+": matches with the this date Pattern:"+datePattern+"Ans:"+isDate); } }
結果
上麵的代碼示例將產生以下結果。
Date :8-05-1988: matches with the this date Pattern: d{1,2}-d{1,2}-d{4}Ans:true Date :08/04/1987: matches with the this date Pattern: d{1,2}-d{1,2}-d{4}Ans:false