try{
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
     System.out.println(sdf.parse("2004-02-34"));
    }catch(Exception e){
      System.out.println("错误日期");
    }
结果为:Fri Mar 05 00:00:00 CST 2004
本来2月份没有34号,可java为什么没有报错呀?

解决方案 »

  1.   

    DateFormat df=DateFormat.getDateInstance();
    df.setLenient(false);
    这样如果日期不对就会抛出异常
      

  2.   

    public static void main(String[] args) {
    // TODO: Add your code here
    try
    {
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
    sdf.setLenient (false);//日期不对,抛出错误!
    //sdf.setLenient (true);//设置宽转换
    String s="2004-01-36";
    Date d=sdf.parse (s);
    String ds=sdf.format (d);
    System.out.println (s);
    System.out.println (ds);
    }
    catch(Exception ex)
    {
    ex.printStackTrace();
    }
    }
      

  3.   

    非常感谢,我想问一下setLenient的意思
      

  4.   

    import java.text.ParseException;/**
     * User: zhuzf
     * Date: 2004-12-23
     * Time: 9:21:53
     */
    public class Test {
        /**
         * 是否有效的日期
         *
         * @param dateStr
         * @param pattern
         * @return
         */
        public static boolean isValidDate(String dateStr, String pattern) {
            java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(pattern);
            try {
                df.setLenient(false);
                df.parse(dateStr);
                return true;
            } catch (ParseException e) {
                return false;        }
        }    public static void main(String[] args) throws Exception {
            System.out.println("19810331 is valid? " + isValidDate("19810331", "yyyyMMdd"));
            System.out.println("19810332 is valid? " + isValidDate("19810332", "yyyyMMdd"));
        }
    }