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?
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).
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
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/
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class TestDate {
public static boolean isValid(String value) {
try {
new SimpleDateFormat("dd/mm/yyyy").parse(value);
return true;
} catch (ParseException e) {
return false;
}
}
}
Try to parse it, if it fails - the format was not correct.
Keep in mind that SimpleDateFormat is not thread safe, so do not reuse the instance from several Threads.