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

tec*_*012 5 java format date

我在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());
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 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
Run Code Online (Sandbox Code Playgroud)

正如乔恩斯基特建议,您还可以设置TimeZoneLocaleSimpleDateFormat

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
Run Code Online (Sandbox Code Playgroud)