回答之前请先阅读下面的代码:
public static void main(String[] args) throws Exception{
    String strDate = "999-999-999";// 定义日期字符串
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");// 定义日期格式
    Date date = null;
try {
    date = format.parse(strDate);// 将字符串转换为日期
} catch (ParseException e) {
    System.out.println("日期格式有误,请给出正确的日期格式");
    return;
}
    System.out.println(format.format(date)); 
}
运行结果是:1084-11-23
预想的结果应该是:日期格式有误,请给出正确的日期格式,但是却输出了日期,很纳闷,求解。javadateexceptionstring

解决方案 »

  1.   

    已经搞定了,在date = format.parse(strDate)前面加上format.setLenient(false)就行了。意思是【严格的解析,输入必须匹配这个对象的格式。】
      

  2.   

    正常下一般人都是调用format方法来去格式化时间。
    parse方法比较繁琐
     /**
         * Parses text from the beginning of the given string to produce a date.
         * The method may not use the entire text of the given string.
         * <p>
         * See the {@link #parse(String, ParsePosition)} method for more information
         * on date parsing.
         *
         * @param source A <code>String</code> whose beginning should be parsed.
         * @return A <code>Date</code> parsed from the string.
         * @exception ParseException if the beginning of the specified string
         *            cannot be parsed.
         */
        public Date parse(String source) throws ParseException
        {
            ParsePosition pos = new ParsePosition(0);
            Date result = parse(source, pos);
            if (pos.index == 0)
                throw new ParseException("Unparseable date: \"" + source + "\"" ,
                    pos.errorIndex);
            return result;
        }
      

  3.   

    谢谢大家的回答,已经搞定了。
    在date = format.parse(strDate)前面加上format.setLenient(false)就行了。
    意思是【指定日期/时间解析是否不严格。进行不严格解析时,解析程序可以使用启发式的方法来解释与此对象的格式不精确匹配的输入。进行严格解析时,输入必须匹配此对象的格式。