最近在工作中需要用到對"yyyyMM"類的日期校驗,比如"201501"就表示2015年1月,然後如果是"201513",“2015qew”等這些這是非法的輸入。
之前使用了一直方式校驗,使用SimpleDateFormat類的parse()方法,該方法會拋出ParseException異常,如果parse不符合format,就會拋出該異常。但後來發現了一個問題,就是這種方法對於"yyyy-MM","yyyy-MM-dd"類格式還可用,但到了"yyyyMM"類的就會出現問題,下面用代碼說明:
public class Test {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM") ;
public static void main(String[] args) {
String testCase1 = "201501";
String testCase2 = "201513234";
String testCase3 = "2015qew";
try {
sdf.parse(testCase1) ;
System.out.println("'"+testCase1+"'沒有發生異常");
sdf.parse(testCase2) ;
System.out.println("'"+testCase2+"'沒有發生異常");
sdf.parse(testCase3) ;
System.out.println("'"+testCase3+"'沒有發生異常");
} catch (ParseException e) {
System.out.println("發生了異常");
}
}
}
運行結果如下:
'201501'沒有發生異常
'201513234'沒有發生異常
發生了異常
從上面可以看出,"201513234"不符合"yyyyMM"形式,但依然沒出現異常,在"201501"纔出現異常,因此這種方式判斷日期格式不安全。
爲此,我們可以使用下面一個方法:
/**
* 判斷時間格式是否是"yyyyMM"或者"yyyyMMdd"
* @param date 字符串類型時間
* @param format 時間格式
* @return
*/
public static boolean isDate(String date , String format){
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date d = sdf.parse(date); //把字符串轉化爲日期(可以過濾掉奇怪格式的日期格式)
String newDate = sdf.format(d);//日期轉化爲字符
/*
*1,把字符串的日期轉化爲Date類型的日期。
*2,把Date類型日期轉化爲字符串類型日期。
*3,如果兩者相等,說明日期格式符合要求
*/
if(null != newDate && newDate.equals(date)){
return true ;
}else {
return false ;
}
} catch (ParseException e) {
//出現異常,說明時間格式有誤
return false ;
}
}
測試:
public static void main(String[] args) {
String testCase1 = "201501";
String testCase2 = "201513234";
String testCase3 = "2015qew";
System.out.println(isDate(testCase1,"yyyyMM"));
System.out.println(isDate(testCase2,"yyyyMM"));
System.out.println(isDate(testCase3,"yyyyMM"));
}
運行結果:
true
false
false