Converting date-string to a different format

…衆ロ難τιáo~ 提交于 2019-11-27 04:23:19

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

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.

Ole V.V.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!