正则表达式,好象是JDK1。4支持吧

解决方案 »

  1.   

    java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.parse(startDate);
      

  2.   

    SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
      try{
        df.parse(startDate);//抛异常就不是正确格式
    }catch(){}
      

  3.   

    //正则表达式
    Pattern p=Pattern.compile("[1-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]");
    Matcher m=p.matcher(startDate);
    if(!m.find()){
    //错误
    }
      

  4.   

    还有没有更好的方法呀?
    SimpleDateFormat 方法不能保证输入的确实是日期,比如:1999-00-01就不能检测出来
    正则表达式不能在JDK1.2上使用,而且SCO UNIX 的JDK好象只有1.2版本的???
    怎么验证是合法日期呀??
      

  5.   

    String s = ...
    java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try
    {
        if(s.equals(sdf.format(sdf.parse(s)))
            //格式正确;
        else
            //格式不正确;
    }
    catch(ParseException e)
    {
            //格式不正确;
    }
      

  6.   

    其实你这个判断包含两部分,一是判断字串是否为****-**-**的形式,而是判断字串是否为日期。
    SimpleDateFormat的函数只能作第一种判断。如果不用正则表达式的话还是自己写函数吧。
    String sDate = "****-**-**";
    // 判断形式
    try {
        if ( (sDate.indexOf("-") == 5) && (sDate.lastIndexOf("-") == 8)) {
            // 形式符合要求,判断是否为日期
            Calendar calendar = Calendar.getInstance();
            Calendar.setLenient( false );
            Calendar.set(Integer.parseInt(sDate.substring(0, 4)),
                         Integer.parseInt(sDate.substring(5, 7)) - 1,// 月份比较特别,要-1才能得到相应的月
                         Integer.parseInt(sDate.substring(8, 10)));
            Date dt = calendar.getTime();
            return true;
        } else {
            // 形式不符合要求
            return false;
        }
    } catch (Exception e) {
        // 非日期
        return false;
    }