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 possible way?
This is how I would do it naively:
import java.util.*;
public class test {
public static void main(String[] args) {
String date = (String) args[0];
System.out.println(date); //outputs: YYYY-MM-DD
System.out.println(doConvert(date)); //outputs: DD-MM-YYYY
}
public static String doConvert(String d) {
String dateRev = "";
String[] dateArr = d.split("-");
for(int i=dateArr.length-1 ; i>=0 ; i--) {
if(i!=dateArr.length-1)
dateRev += "-";
dateRev += dateArr[i];
}
return dateRev;
}
}
But are there any other, more elegant AND effective way of doing it? Ie. using some built-in feature? I have not been able to find one, while quickly searching the API.
Anyone here know an alternative way?
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.
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.
Use
java.util.DateFormat
:Here’s the modern answer.
With this we may do for example:
This prints
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 usingSimpleDateFormat
andDate
. The newer classes are much more programmer friendly and nice to work with.