techsjs2012
techsjs2012

Reputation: 1737

Taking a String that is a Date and Formatting it in Java

I have a String in Java which is a date but is formatted like:

02122012

I need to reformat it to look like 02/12/2012 how can this be done.

With the following code I keep getting back java.text.SimpleDateFormat@d936eac0

Below is my code..

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());
}

Upvotes: 5

Views: 491

Answers (2)

Alex
Alex

Reputation: 25613

Use SimpleDateFormat.

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

As suggested by Jon Skeet, you can also set the TimeZone and Locale on the SimpleDateFormat

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

Upvotes: 9

Jon Skeet
Jon Skeet

Reputation: 1499730

This is the problem with the code in your edited question:

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

You're printing out the SimpleDateFormat, not the result of calling format. Indeed, you're ignoring the result of calling format:

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

Just change it to:

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

Or more clearly:

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

Upvotes: 0

Related Questions