闲来无事,写了几篇关于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;
        }
        return true;
    }

解决方案 »

  1.   

    楼主真的很闲啊,我以前也自己写了一个,现丑下,呵呵.
    -------------------------------
    public static boolean checkDate(String date){
    boolean rtn = false;
    try{
    SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
    String newDate = sd.format(sd.parse(date));
    if(date.equals(newDate))rtn = true;

    }catch(Exception e){e.printStackTrace();}

    return rtn;

    }纯粹是弄着玩.
      

  2.   

    public static boolean checkDate(String date){
    boolean rtn = false;
    try{
    SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
    String newDate = sd.format(sd.parse(date));
    if(date.equals(newDate))rtn = true;

    }catch(Exception e){e.printStackTrace();}

    return rtn;

    }这个都被你想出来了,果然牛!!!!!
    赫赫
      

  3.   

    我们一般直接js判断的当然要在java里判断我一般用的是shan1119的方法,这里也发个我js写的
    //短时间形如 (1984-06-03)
          function checkDateTime(str)
          {
             var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
             if(r==null)return false;
             var d= new Date(r[1], r[3]-1, r[4]);
             return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
          }