Converting date-string to a different format

lobner picture lobner · Jul 9, 2011 · Viewed 28.5k times · Source

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?

Answer

duffymo picture duffymo · Jul 9, 2011

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