import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CheckDateFormat {
public static void main(String... args) {
Date date = checkDates("2016-01-01");
System.out.println(date);
date = checkDates("2016-13-01");
System.out.println(date); //returns null
date = checkDates("03/22/1974");
System.out.println(date); //returns null
}
public static Date checkDates(String text) {
// http://howtodoinjava.com/regex/java-regex-date-format-validation/
// https://www.debuggex.com/r/7jAhBMayS28ezOAN/4
SimpleDateFormat df = null;
if (text != null) {
if (text.matches("\\d{4}-[01]\\d-[0-3]\\d")) {
//http://stackoverflow.com/questions/2149680/regex-date-format-validation-on-java
df = new SimpleDateFormat("yyyy-MM-dd");
} else if (text.matches("/^(0[1-9]|1[0-2])\\/(0[1-9]|1\\d|2\\d|3[01])\\/(19|20)\\d{2}$/")) {
//http://stackoverflow.com/questions/15196451/regular-expression-to-validate-datetime-format-mm-dd-yyyy
df = new SimpleDateFormat("MM/DD/YYYY");
} else if (text.matches("/^(\\d{1,2})-(\\d{1,2})-(\\d{4})$/")) {
//http://stackoverflow.com/questions/8937408/regular-expression-for-date-format-dd-mm-yyyy-in-javascript
df = new SimpleDateFormat("dd-mm-yyyy");
// } else if (text.matches("0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d")) {
// //http://stackoverflow.com/questions/8937408/regular-expression-for-date-format-dd-mm-yyyy-in-javascript
// df = new SimpleDateFormat("dd/mm/yyyy");
}
if (df == null) return null; // didnt match any regex parser
df.setLenient(false);
try {
return df.parse(text);
} catch (ParseException ex) {
return null;
}
}
return null;
}
}
0 comments:
Post a Comment