Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

date

format

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());
}
like image 910
techsjs2012 Avatar asked Nov 14 '12 18:11

techsjs2012


People also ask

How do you format a date in Java?

Java SimpleDateFormat ExampleString pattern = "MM-dd-yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat. format(new Date()); System. out. println(date);


1 Answers

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
like image 88
Alex Avatar answered Oct 17 '22 06:10

Alex