This question already has an answer here:
- How to convert String to Date without knowing the format? 9 answers
I am facing issue related to date format pattern. Suppose user gives wrong input like this
'200000-05-16'
and I have format like this mm/dd/yyyy
. I want to check format in java class the input date is wrong.
How is it possible to do in java?
Here is two solutions. I recommend the second one (the mkyong tutorial).
Solution 1 (Regexp)
String datePattern = "\\d{2}-\\d{2}-\\d{4}";
String date1 = "200000-05-16";
String date2 = "05-16-2000";
Boolean isDate1 = date1.matches(datePattern);
Boolean isDate2 = date2.matches(datePattern);
System.out.println(isDate1);
System.out.println(isDate2);
Output :
false
true
The pattern is not the better one because you could pass "99" as a month or a day and it will be ok. Please check this post for a good pattern : Regex to validate date format dd/mm/yyyy
Solution 2 (SimpleDateFormat)
This solution take a SimpleDateFormat to check if it is valid or not. Please check this link for a complete and great solution : http://www.mkyong.com/java/how-to-check-if-date-is-valid-in-java/
0 comments:
Post a Comment