Java:SimpleDataFormat在解析时抛出异常

fel*_*ipe 3 java simpledateformat

我使用SimpleDataFormat多年了.我从来没有得到这个Exception

程序在下面,我从互联网上得到了一个例子的代码:

    public static void main(String[] args) {
    // Make a new Date object. It will be initialized to the
    // current time.
    Date now = new Date();

    // Print the result of toString()
    String dateString = now.toString();
    System.out.println(" 1. " + dateString);

    // Make a SimpleDateFormat for toString()'s output. This
    // has short (text) date, a space, short (text) month, a space,
    // 2-digit date, a space, hour (0-23), minute, second, a space,
    // short timezone, a final space, and a long year.
    SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

    // See if we can parse the output of Date.toString()
    try {
        Date parsed = format.parse(dateString);
        System.out.println(" 2. " + parsed.toString());
    }
    catch(ParseException pe) {
        System.out.println("ERROR: Cannot parse \"" + dateString + "\"");
    }

    // Print the result of formatting the now Date to see if the result
    // is the same as the output of toString()
    System.out.println(" 3. " + format.format(now));
}
Run Code Online (Sandbox Code Playgroud)

好的很简单.

结果:

 1. Wed Aug 08 13:49:05 BRT 2012
    ERROR: Cannot parse "Wed Aug 08 13:49:05 BRT 2012"
 3. Qua Ago 08 13:49:05 BRT 2012
Run Code Online (Sandbox Code Playgroud)

你看到2.抛出一个错误?对我来说,这一切都是正确的.

我应该设置任何语言环境的东西吗?

我的操作系统:Windows 7 Proffesional,Service Pack 1 JDK:jdk1.6.0_25

Jon*_*eet 9

它看起来像是一个语言环境问题,是的.如果你查看输出,它不使用英文月份和日期名称 - 所以它也无法解析它们.在创建时尝试指定英语SimpleDateFormat:

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",
                                               Locale.US);
Run Code Online (Sandbox Code Playgroud)