Tuesday, 28 July 2015

Date validation with Java

This is a date validation with. It will validate the date forma(yyyy-MM-dd), valid month date/month and leap year.



private static String RUN_DATE_REGEX = "((20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])";

private static Pattern datePattern = Pattern.compile(RUN_DATE_REGEX);
private static Matcher dateMatcher;

public static boolean isDateValid(final String dateString){
dateMatcher = datePattern.matcher(dateString);
if(dateMatcher.matches()){
   dateMatcher.reset();
   if(dateMatcher.find()){
String[] dateArr = dateString.split("-");
int year = Integer.parseInt(dateArr[0]);
int month = Integer.parseInt(dateArr[1]);
int day = Integer.parseInt(dateArr[2]);
if((day ==31) && (month == 4 || month == 6|| month == 9 || month == 11)){
   return false; // 1,3,5,7,8,10,12 has 31 days
}else if(month == 2){
   
   if((day == 30) || (day == 31)){
return false;
   }
   
   if((year % 4) != 0){
if(day == 29){
   return false;
}
   }
   return true;
}else{
   return true;
}
   }
}
return false;
    }

No comments:

Post a Comment