javadatetimedate

Java - Date constructor accepts a Date String, But deprecated. Tried alternatives, but no luck


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"

Solution

  • Your parsing pattern is wrong. It does not match the date string representation. The MMM denotes a 3-letter localized month abbreviation, while you have 2-digit month number in your actual date, you need MM. You've also slashes / as date/month/year separator and not -. For the AM/PM marker you also need an a afterwards so that the right hh can be parsed.

    This should work:

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"); 
    

    For an explanation of those patterns, read the SimpleDateFormat javadoc.


    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 a into another date string format, as specified by the pattern MMM-dd-yyyy hh:mm:ss. In that case, you should then have two SimpleDateFormat instances, one which parses the string in the given pattern to a Date and another which formats the parsed Date to the given pattern. This should do what you want:

    String inputDate = "07/28/2011 11:06:37 AM";
    Date date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a").parse(inputDate);
    String outputDate = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss").format(date);
    System.out.println(outputDate); // Jul-28-2011 11:06:37
    

    Note that I changed hh in output to be HH because it would otherwise end up in 1-12 hour representation without an AM/PM marker. The HH represents it as 0-23 hour.