how to convert java string to Date object

user755043 picture user755043 · Jun 28, 2011 · Viewed 571.5k times · Source

I have a string

String startDate = "06/27/2007";

now i have to get Date object. My DateObject should be the same value as of startDate.

I am doing like this

DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
Date startDate = df.parse(startDate);

But the output is in format

Jan 27 00:06:00 PST 2007.

Answer

citizen conn picture citizen conn · Jun 28, 2011

You basically effectively converted your date in a string format to a date object. If you print it out at that point, you will get the standard date formatting output. In order to format it after that, you then need to convert it back to a date object with a specified format (already specified previously)

String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
Date startDate;
try {
    startDate = df.parse(startDateString);
    String newDateString = df.format(startDate);
    System.out.println(newDateString);
} catch (ParseException e) {
    e.printStackTrace();
}