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?
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));
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