Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting date-string to a different format

Tags:

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?

like image 710
lobner Avatar asked Jul 09 '11 21:07

lobner


1 Answers

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)); 
like image 179
duffymo Avatar answered Oct 31 '22 08:10

duffymo