通常我們會遇到需要檢測一個像"20040531"這樣的日期是不是合法,因為不知道這個月又沒有31天等等,于是寫了一個簡單
實用的日期檢測工具函數(shù),他利用了Calendar的一個Lenient屬性,設(shè)置這個方法為false時,便打開了對Calendar中日期的
嚴(yán)格檢查,注意一定要調(diào)用了cal.getTime()方法的時候才會拋出異常,否則就不能檢測成功.
import java.util.Calendar;
/**
*
* 日期檢測工具類
* @author zming
* (http://blog.jweb.cn)
* (http://m.tkk7.com/zming)
*/
public class DateCheck {
public static void main(String[] args) {
System.out.println("check 1:"+checkValidDate("20050123"));
System.out.println("check 2:"+checkValidDate("20050133"));
}
/**
* 日期檢測工具類
* @param pDateObj 日期字符串
* @return 整型的結(jié)果
*/
public static boolean checkValidDate( String pDateObj ) {
boolean ret = true;
if ( pDateObj==null || pDateObj.length() != 8 )
{
ret = false;
}
try {
int year = new Integer(pDateObj.substring( 0, 4 )).intValue();
int month = new Integer(pDateObj.substring( 4, 6 )).intValue();
int day = new Integer(pDateObj.substring( 6 )).intValue();
Calendar cal = Calendar.getInstance();
//允許嚴(yán)格檢查日期格式
cal.setLenient( false );
cal.set(year, month-1, day);
//該方法調(diào)用就會拋出異常
cal.getTime();
} catch( Exception e ) {
ret = false;
}
return ret;
}
}