Converting date-string to a different format

28,993

Solution 1

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

Solution 2

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.

Solution 3

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.

Solution 4

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)

Solution 5

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

Share:
28,993
lobner
Author by

lobner

BSc. Computer Science, Copenhagen, Denmark. Find/contact me on facebook, twitter, linkedin or my personal website. SOreadytohelp

Updated on July 18, 2022

Comments

  • lobner
    lobner almost 2 years

    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?