通常我們會(huì)遇到需要檢測(cè)一個(gè)像"20040531"這樣的日期是不是合法,因?yàn)椴恢肋@個(gè)月又沒(méi)有31天等等,于是寫了一個(gè)簡(jiǎn)單
實(shí)用的日期檢測(cè)工具函數(shù),他利用了Calendar的一個(gè)Lenient屬性,設(shè)置這個(gè)方法為false時(shí),便打開了對(duì)Calendar中日期的
嚴(yán)格檢查,注意一定要調(diào)用了cal.getTime()方法的時(shí)候才會(huì)拋出異常,否則就不能檢測(cè)成功.
import java.util.Calendar;
/**
*
* 日期檢測(cè)工具類
* @author zming
* (http://blog.jweb.cn)
* (http://www.aygfsteel.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"));
}
/**
* 日期檢測(cè)工具類
* @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)用就會(huì)拋出異常
cal.getTime();
} catch( Exception e ) {
ret = false;
}
return ret;
}
}