I have a string containing a date in the format YYYY-MM-DD
.
How would you suggest I go about converting it to the format DD-MM-YYYY
in the
Best to use a SimpleDateFormat (API) object to convert the String to a Date object. You can then convert via another SimpleDateFormat object to whatever String representation you wish giving you tremendous flexibility.
import java.util.DateFormat;
// Convert String Date To Another String Date
public String convertStringDateToAnotherStringDate(String stringdate, String stringdateformat, String returndateformat){
try {
Date date = new SimpleDateFormat(stringdateformat).parse(stringdate);
String returndate = new SimpleDateFormat(returndateformat).format(date);
return returndate;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
//-------
String resultDate = convertStringDateToAnotherStringDate("1997-01-20", "yyyy-MM-dd", "MM/dd/yyyy")
System.out.println(resultDate);
Result (date string) : 01/20/1997
Use java.util.DateFormat
:
DateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd");
fromFormat.setLenient(false);
DateFormat toFormat = new SimpleDateFormat("dd-MM-yyyy");
toFormat.setLenient(false);
String dateStr = "2011-07-09";
Date date = fromFormat.parse(dateStr);
System.out.println(toFormat.format(date));
Here’s the modern answer.
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
public static String doConvert(String d) {
return LocalDate.parse(d).format(formatter);
}
With this we may do for example:
System.out.println(doConvert("2017-06-30"));
This prints
30-06-2017
I am exploiting the fact that the format you have, YYYY-MM-DD
, conforms with the ISO 8601 standard, a standard that the modern Java date and time classes “understand” natively, so we need no explicit formatter for parsing, only one for formatting.
When this question was asked in 2011, SimpleDateFormat
was also the answer I would have given. The newer date and time API came out with Java 8 early in 2014 and has also been backported to Java 6 and 7 in the ThreeTen-Backport project. For Android, see the ThreeTenABP project. So these days honestly I see no excuse for still using SimpleDateFormat
and Date
. The newer classes are much more programmer friendly and nice to work with.
If you're not looking for String to Date conversion and vice-versa, and thus don't need to handle invalid dates or anything, String manipulation is the easiest and most efficient way. But i's much less readable and maintainable than using DateFormat.
String dateInNewFormat = dateInOldFormat.substring(8)
+ dateInOldFormat.substring(4, 8)
+ dateInOldFormat.substring(0, 4)