How to check check whether date is in proper format or not?
Solution:
Following example demonstrates how to check whether the date is in a proper format or not using matches method of String class.
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);
}
}
Result:
The above code sample will produce the following result.
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