24

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?

lobner
  • 593
  • 1
  • 7
  • 15

5 Answers5

45

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));
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • Definitely more elegant. But would you also argue that it is more effective? It is for an Android app. And the only string formats worked with are the ones mentioned. – lobner Jul 09 '11 at 21:53
  • @lobner: what if you want to store the date? Better to store it as a Date object rather than a String. – Hovercraft Full Of Eels Jul 10 '11 at 02:54
  • @Hovercraft: I have been convinced :) using [Settings.System.html#DATE_FORMAT](http://developer.android.com/reference/android/provider/Settings.System.html#DATE_FORMAT) I can use the date format the user perfers. Thus I make Date objects, and all is good. – lobner Jul 10 '11 at 05:09
5

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
4

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
2

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)
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • This actually solves my particular problem exactly like I intended. Simple and elegant. And as I, as mentioned, don't need any other formats, this is the winner :) – lobner Jul 09 '11 at 22:12
  • 2
    @lobner: I beg to differ. The minute you need something in a different format, you're going to have to redo all again. What if you want to save the date? Do you save it as a String? Which format? Using a Date object is in general preferred due to flexibility and universality. This answer here is good, but is more of a quick and dirty solution. – Hovercraft Full Of Eels Jul 10 '11 at 02:53
  • @Hovercraft: I stand corrected. I actually only needed the 'quick and dirty' but along the way, I changed the responsibility and requirements of the application. – lobner Jul 10 '11 at 06:24
1
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

Krunal
  • 77,632
  • 48
  • 245
  • 261
  • 1
    While in 2011 when this question was asked I would have agreed to using `SimpleDateFormat`, it is now long outdated, and it is much better to use the modern Java date and time API. – Ole V.V. Jun 30 '17 at 16:36