Gnaniyar Zubair Gnaniyar Zubair - 7 months ago 14
Java Question

Parse String to Date with Different Format in Java

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

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();
}
Comments