程序支持校验标准yyyyMMdd日期格式,支持平年闰年29日、大小月的31日的校验
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckDateFormat {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
String str="20210229";
System.out.println(isValidDate1(str));//612
System.out.println(isValidDate2(str));//804
System.out.println(isValidDate3(str));//259
}
/**
* 方法一:判断字符串是否为日期格式,利用日期类DateFormat类parse方法校验
*/
public static boolean isValidDate1(String inDate){
if(inDate==null){
return false;
}
SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMdd");//或yyyy-MM-dd
if(inDate.trim().length() != dataFormat.toPattern().length()){
return false;
}
dataFormat.setLenient(false);//该方法用于设置Calendar严格解析字符串;默认为true,宽松解析
try {
dataFormat.parse(inDate.trim());
} catch (ParseException e) {
return false;
}
return true;
}
/**
* 方法二:判断字符串是否为日期格式,利用正则表达式方法校验
*/
public static boolean isValidDate2(String strDate) {
Pattern pattern = Pattern .compile("^((\\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]))))))(\\s(((0?[0-9])|([1-2]"
+ "[0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
Matcher m = pattern.matcher(strDate);
return (m.matches())?true:false;
}
/**
* 方法三:判断字符串是否为日期格式,利用日期组合规则校验
*/
public static boolean isValidDate3(String inDate){
int year = Integer.parseInt(inDate.substring(0,4));//年份
int month = Integer.parseInt(inDate.substring(4,6));//月份
int day = Integer.parseInt(inDate.substring(6,8));//天数
if (month < 1 || month > 12) {//校验月份格式
return false;
}
if (day < 1 || day > 31) {//校验天数格式
return false;
}
if ((month == 4 || month == 6 || month == 9 || month == 11) &&(day == 31)) {//是否不符合4月、6月、9月、11月最大天数30日
return false;
}
boolean leap=false;
if (month == 2) {//闰年2月为29天,平年2月为28天
leap = (year % 4 == 0 &&(year % 100 != 0 || year % 400 == 0));
if (day>29 || (day == 29 && !leap)) {
return false;
}
}
return true;
}
}