请问下面的代码运行时会抛异常么,为什么?package november;import java.text.ParseException;
import java.text.SimpleDateFormat;public class TestParse {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
System.out.println(sdf.parse("2007-09-06"));
}
}

解决方案 »

  1.   

    Please read the API in detail carefully.
    Your date format is wrong. Please study that.
    SimpleDateFormat   sdf   =   new   SimpleDateFormat( "yyyy-MM-dd");
    System.out.println(sdf.parse( "2007-09-06 ")); 
      

  2.   


    import   java.text.ParseException;
    import   java.text.SimpleDateFormat;public   class   TestParse   {
    public   static   void   main(String[]   args)   throws   ParseException   {
    SimpleDateFormat   sdf   =   new   SimpleDateFormat( "yyyyMMdd ");
    System.out.println(sdf.parse( "20070906 "));
    }
    }
      

  3.   

    我没办法修改帖子,我想问的是这段代码为什么没抛异常?
    Console:Sat Dec 09 00:00:00 CST 2006
    我本意是捕获异常后进行处理的,可它居然没抛异常,傻眼了,有谁知道为什么?
      

  4.   

    There is no doubt that your code throws java.text.ParseException. It should tell you something like "Unparsable date ...".
      

  5.   

    ..........这个当然不会异常了......用"yyyyMMdd"来parse "2007-09-06"就读取了前面的  "2007-09-" ("2007" "-0" "9-"),而在DataFormat里面,"-"就是空也就是,SimpleDateFormat 后的日期是 2007-00-09
    月份是从1开始的....所以00月就是上一年的12月
    所以日期就成了 2006-12-09
      

  6.   

    原来是这样啊,我明白了,谢谢Kreocn,这是我第一次在csdn上提问,就有人给出了正确的解答,感觉还是很不错的。是不是可以给你加分啊。
    不忘BS一下5楼的外国朋友,我说那么清楚了还...
      

  7.   

    不对,差点让Kreocn给忽悠了,“而在DataFormat里面, "- "就是空”,就是你哪里看来的啊。
    我说文档中怎么没找到呢。
    你瞎扯吧,整个一胡说,还好还没给你分,比人家不回答还可恶,作为程序员应该是严谨的,怎么能想当然呢。
    我还是自己查吧,解决了会公布出来的,现在要吃饭去了。
    还有,别在给我说“毫无疑问抛异常了”,拜托!
      

  8.   

    这是java doc中关于parse()的描述。
    parse
    public Date parse(String text,
                      ParsePosition pos)分析字符串的文本,生成 Date。 
    此方法试图分析从 pos 给定的索引处开始的文本。如果分析成功,则将 pos 的索引更新为所用最后一个字符后面的索引(不必对直到字符串结尾的所有字符进行分析),并返回分析得到的日期。更新后的 pos 可以用来指示下次调用此方法的起始点。如果发生错误,则不更改 pos 的索引,并将 pos 的错误索引设置为发生错误处的字符索引,并且返回 null。 
    指定者:
    类 DateFormat 中的 parse
    参数:
    text - 应该分析其中一部分的 String。
    pos - 具有以上所述的索引和错误索引信息的 ParsePosition 对象。 
    返回:
    从字符串进行分析的 Date。如果发生错误,则返回 null。 
    抛出: 
    NullPointerException - 如果 text 或 pos 为 null。
    另请参见:
    DateFormat.setLenient(boolean)
    再看一下DateFormat.parse(String source, ParsePosition pos)中的这段话,
    在默认情况下,进行的分析是不严格的:如果输入的形式不是此对象的格式化方法使用的形式,但仍可作为日期进行分析,则分析将获得成功。客户机可能通过调用 setLenient(false) 来强调严格遵守该格式。如果在输出之前加上sdf.setLenient(false);
    就会捕获异常:
    java.text.ParseException: Unparseable date: "2007-09-06 "
    at java.text.DateFormat.parse(DateFormat.java:335)
    at encrypt.DotSplit.main(DotSplit.java:12)