SimpleDateFormat:意外的结果和意外的解析异常

SimpleDateFormat: unexpected results and unexpected parse exceptions

我在使用简单的日期格式时遇到了很大的困难。首先,我知道并非所有站点上的所有教程实际上都很好,但是所有非平凡格式(不是 dd/MM/yyyy)都给出了解析异常(加上我自己的测试没有按预期工作)这一事实相当让我很沮丧。

这是有问题的站点:http://www.mkyong.com/java/how-to-convert-string-to-date-java/

而且我不明白为什么像这样简单的事情:

private static void unexpectedFailure() {
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
    String dateInString = "7-Jun-2013";

    try {

        Date date = formatter.parse(dateInString);
        System.out.println(date);
        System.out.println(formatter.format(date));

    } catch (ParseException e) {
        e.printStackTrace();
    }
}

抛出解析异常。

除此之外,我正在尝试解析我自己的日期。这段代码给出了奇怪的结果(我会说出乎意料):

public static void doSomething(List<String> list) { 
    Iterator<String> iter = list.iterator();
    String[] line = iter.next().split(" ");
    System.out.println(Arrays.toString(line));
    DateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
    format.setLenient(true);


    try {
        System.out.println(line[0]+" "+line[1]);
        System.out.println(format.parse(line[0]+" "+line[1]));
    } catch (ParseException e) {
        System.out.println("In theory this should not get caught.");
    }
}

打印出来:

[06/08/2015, 13:51:29:849, DEBUG, etc...]
06/08/2015 13:51:29:849
Thu Aug 06 13:51:29 EEST 2015

Thu Aug 06 13:51:29 EEST 2015 什么?为什么?

编辑 我会尽力解释。在我的最后一个代码片段中,我只是试图确定该字符串是否是一个日期,并且它通过了 "the test"。然而,当我打印出来时,格式简直是奇怪。我开始认为那是因为我正在打印日期。我怎样才能打印 DateFormat?我期待的是 dd/MM/yyyy hh:mm:ss 而不是 ddd MMM 06? hh:mm:ss G YYYY

And I don't understand why something as simple as:
(code snipped)
Throws a parse exception.

我的猜测是它被 Jun 绊倒了,这在您的系统默认语言环境中可能不是有效的月份缩写。我建议您在 SimpleDateFormat 构造函数中指定语言环境:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);

然后你要处理的语言环境肯定Jun作为月份的缩写。

也就是说,我建议尽可能使用数字格式,最好是遵循 ISO-8601 的格式,例如

yyyy-MM-dd'T'HH:mm:ss

However when I'm printing it out the format is simply bizzare.

不,不是。您有效地使用了

Date date = format.parse(line[0]+" "+line[1]);
System.out.println(date);

所以调用 Date.toString()documented 为:

Converts this Date object to a String of the form:

dow mon dd hh:mm:ss zzz yyyy

所以这是按预期工作的。但是,您想使用 SimpleDateFormat 格式化 日期 - 因此您需要调用 format:

System.out.println(format.format(date));

当然,基本上只是检查它是否可以往返。

附带说明一下,我怀疑您希望在格式字符串中使用 HH(24 小时制)而不是 hh(12 小时制)。