Parse String to Date with Different Format in Java

Gnaniyar Zubair picture Gnaniyar Zubair · May 19, 2009 · Viewed 310k times · Source

I want to convert String to Date in different formats.

For example,

I am getting from user,

String fromDate = "19/05/2009"; // i.e. (dd/MM/yyyy) format

I want to convert this fromDate as a Date object of "yyyy-MM-dd" format

How can I do this?

Answer

Michael Myers picture Michael Myers · May 19, 2009

Take a look at SimpleDateFormat. The code goes something like this:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

try {

    String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
    e.printStackTrace();
}