用正则表达式匹配,从1970-01-01开始往后2万天逐一测试日期有效性,包括闰年2月29日,都可以校验通过。
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TempTest {
public static void main(String[] args) throws Exception {
Date date = new Date(0);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar cale = Calendar.getInstance();
cale.setTime(date);
for (int i = 0; i < 20000; i++) {
if (!isValidDate(df.format(date))) {
System.out.println("校验失败:" + df.format(date));
}
cale.add(Calendar.DAY_OF_YEAR, 1);
}
System.out.println(df.format(cale.getTime()) + " End.");
}
/**
* 判断日期格式:yyyy-mm-dd
*
* @param sDate
* @return
*/
public static boolean isValidDate(String sDate) {
String datePattern1 = "\\d{4}-\\d{2}-\\d{2}";
String datePattern2 = "^((\\d{2}(([02468][048])|([13579][26]))"
+ "[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|"
+ "(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?"
+ "((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?("
+ "(((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?"
+ "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
if ((sDate != null)) {
Pattern pattern = Pattern.compile(datePattern1);
Matcher match = pattern.matcher(sDate);
if (match.matches()) {
pattern = Pattern.compile(datePattern2);
match = pattern.matcher(sDate);
return match.matches();
} else {
return false;
}
}
return false;
}
}