Taking a String that is a Date and Formatting it in Java
date, format, java
Solution
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
Problem
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()); } ```