获取一个日期字符串并在Java中格式化它

时间:2012-11-14 18:44:42

标签: java date format

我在Java中有一个String,它是一个日期,但格式如下:

02122012

我需要将其重新格式化为 02/12/2012 如何做到这一点。

使用以下代码我一直回到 java.text.SimpleDateFormat@d936eac0

以下是我的代码..

public static void main(String[] args) {

    // Make a String that has a date in it, with MEDIUM date format
    // and SHORT time format.
    String dateString = "02152012";

    SimpleDateFormat input = new SimpleDateFormat("ddMMyyyy");
    SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");
    try {
        output.format(input.parse(dateString));
    } catch (Exception e) {

    }
    System.out.println(output.toString());
}

2 个答案:

答案 0 :(得分:9)

使用SimpleDateFormat。

SimpleDateFormat input = new SimpleDateFormat("ddMMyyyy");
SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(output.format(input.parse("02122012"))); // 02/12/2012

根据Jon Skeet的建议,您还可以在TimeZone上设置LocaleSimpleDateFormat

SimpleDateFormat englishUtcDateFormat(String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    return sdf;
}

SimpleDateFormat input = englishUtcDateFormat("ddMMyyyy");
SimpleDateFormat output = englishUtcDateFormat("dd/MM/yyyy");
System.out.println(output.format(input.parse("02122012"))); // 02/12/2012

答案 1 :(得分:0)

这是您编辑的问题中代码的问题:

System.out.println(output.toString());

您正在打印SimpleDateFormat,而非打印format的结果。实际上,你忽略调用format的结果:

output.format(input.parse(dateString));

只需将其更改为:

System.out.println(output.format(input.parse(dateString)));

或者更清楚:

Date parsedDate = input.parse(dateString);
String reformattedDate = output.format(parsedDate);
System.out.println(reformattedDate);