Java - The Date constructor accepts a Date string, but is not recommended. 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); 

It 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 is an exception:

 java.text.ParseException: Unparseable date: "07/28/2011 11:06:37 AM" 
+4
source share
3 answers

Your analysis template is incorrect. It does not match the representation of the date string. MMM stands for the 3-letter localized abbreviation of the month, while you have a 2-digit month number in your actual date, you need MM . You also abbreviate / as a date / month / year separator, not - . For the AM / PM marker, you'll also need a so you can analyze the right hh .

This should work:

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

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


I believe your specific functional requirement is to convert the given date string specified in the MM/dd/yyyy hh:mm:ss a pattern to a different date string format as specified in the MMM-dd-yyyy hh:mm:ss pattern MMM-dd-yyyy hh:mm:ss . In this case, you should have two instances of SimpleDateFormat , which parses the string in this template for Date and another that formats the parsed Date to this template. 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 the output hh to hh , because otherwise it would have remained in the 1-12 hour view without the AM / PM marker. hh presents it as 0-23 hours.

+11
source

The format you gave SimpleDateFormat uses - between the month, date, and year. Your string uses slashes.

+1
source

First, look that your format string is incorrect.

MMM - You indicated this for a month, but you do not pass the month 3 char.

Try MM and see if this helps.

Take a look at this for more information on the date format:

http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm

+1
source

All Articles