String temp_date="07/28/2011 11:06:37 AM";
Date date = new Date(temp_date); //Depricated
SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss");
String comp_date= sdf.format(date);
System.out.println(comp_date);
This works, But If I use something like this
String temp_date="07/28/2011 11:06:37 AM";
try{
SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss");
Date comp_date= sdf.parse(temp_date);
System.out.println(comp_date);
}catch(Exception e){
System.out.println(e);
}
This exception is thrown:
java.text.ParseException: Unparseable date: "07/28/2011 11:06:37 AM"
Your parsing pattern is wrong. It does not match the date string representation. The
MMMdenotes a 3-letter localized month abbreviation, while you have 2-digit month number in your actual date, you needMM. You’ve also slashes/as date/month/year separator and not-. For the AM/PM marker you also need anaafterwards so that the righthhcan be parsed.This should work:
For an explanation of those patterns, read the
SimpleDateFormatjavadoc.I believe that your concrete functional requirement is to convert the given date string as specified by the pattern
MM/dd/yyyy hh:mm:ss ainto another date string format, as specified by the patternMMM-dd-yyyy hh:mm:ss. In that case, you should then have twoSimpleDateFormatinstances, one which parses the string in the given pattern to aDateand another which formats the parsedDateto the given pattern. This should do what you want:Note that I changed
hhin output to beHHbecause it would otherwise end up in 1-12 hour representation without an AM/PM marker. TheHHrepresents it as 0-23 hour.