public static void main(String[] args) {
String str1="2020-8-6";
String str2="2020-08-06";
String str3="2020-8-32";
String str4="2020-08-32";
String str5 = "2020年-2月";
String str6 = "仨啊是";
String str7 = "sasa";
System.out.println(check(str1));
System.out.println(check(str2));
System.out.println(check(str3));
System.out.println(check(str4));
System.out.println(check(str5));
System.out.println(check(str6));
System.out.println(check(str7));
}
//验证日期是否合法
static boolean check (String str) {
SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd");//括号内为日期格式,y代表年份,M代表年份中的月份(为避免与小时中的分钟数m冲突,此处用M),d代表月份中的天数
try {
sd.setLenient(false);//此处指定日期/时间解析是否不严格,在true是不严格,false时为严格
sd.parse(str);//从给定字符串的开始解析文本,以生成一个日期
}
catch (Exception e) {
return false;
}
return true;
}
输出结果:true
true
false
false
false
false
false