Reputation: 8790
I am trying to convert date from one format to other format but the following code is giving me the exception: please help
public class Formatter {
public static void main(String args[]) {
String date = "12-10-2012";
try {
Date formattedDate = parseDate(date, "MM/dd/yyyy");
System.out.println(formattedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Date parseDate(String date, String format)
throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.parse(date);
}
}
Upvotes: 1
Views: 8670
Reputation: 3990
To convert from "MM-dd-yyyy" to "MM/dd/yyyy" you have to do as follows:
SimpleDateFormat format1 = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("MM/dd/yyyy");
Date date = format1.parse("12-10-2012");
System.out.println(format2.format(date));
If you input "12-10-2012"
then output will be "12/10/2012"
:
Upvotes: 11
Reputation: 3434
Try this.
Date formattedDate = parseDate(date, "MM-dd-yyyy");
Upvotes: 1
Reputation: 7297
Your format uses slashes (/) but the date you supply uses dashes (-). Change to:
Date formattedDate = parseDate(date, "MM-dd-yyyy");
And you should be good :)
Upvotes: 5
Reputation: 40416
change slash /
to dash -
MM-dd-yyyy instead of MM/dd/yyyy
it should be Date formattedDate = parseDate(date, "MM-dd-yyyy");
Upvotes: 6