日期:2014-05-20  浏览次数:20829 次

[闭月羞花猫]check日期是否合法 non-lenient 模式
闲来无事,写了几篇关于web开发过程中,一些基础的应用。
希望能够对初学者有所帮助。

不足的地方,也希望高手能够给与指正。  

功能:   check日期是否合法   (主要实现某年某月日期是否超过当月最大日期的合法性判断)
    测试数据:       20070229                 false
                                    20070228                 false
                                    20040229                 true

  /**
          *   日期合法check
          *  
          *   @param   date   需要check的日期
          *   @return   日期是否合法
          */
        public   static   boolean   chkDateFormat(String   date)   {
                try   {
                      //   如果输入日期不是8位的,判定为false.  
                        if   (null   ==   date   ||   " ".equals(date)   ||   !date.matches( "[0-9]{8} "))   {
                                return   false;
                        }
                        int   year   =   Integer.parseInt(date.substring(0,   4));
                        int   month   =   Integer.parseInt(date.substring(4,   6))   -   1;
                        int   day   =   Integer.parseInt(date.substring(6));
                        Calendar   calendar   =   GregorianCalendar.getInstance();
                        //   当   Calendar   处于   non-lenient   模式时,如果其日历字段中存在任何不一致性,它都会抛出一个异常。
                        calendar.setLenient(false);
                        calendar.set(Calendar.YEAR,   year);
                        calendar.set(Calendar.MONTH,   month);
                        calendar.set(Calendar.DATE,   day);
                      //   如果日期错误,执行该语句,必定抛出异常.
                        calendar.get(Calendar.YEAR);
                }   catch   (IllegalArgumentException   e)   {
                        return   false;
                }