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());
}
Java SimpleDateFormat ExampleString pattern = "MM-dd-yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat. format(new Date()); System. out. println(date);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With