Jayizzle Jayizzle - 4 months ago 27
Java Question

Unparsable Date in Java: Basic Calendar instance parse issues with SimpleDateFormat

I am trying to parse the current time and date into this simple date format.

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy-kk:mm");
Date datetoday = sdf.parse(Calendar.getInstance().getTime().toString());

However, I get this.

java.text.ParseException: Unparseable date: "Tue May 17 15:28:36 CDT 2016"

I'm still able to parse Strings like: 5/5/1991-12:00 but when given a Calendar Instance, it blows up. I really should have used JodaTime from the get go.

How can I just get the current time, into the SimpleDateFormat as it is? As I understood it, the SimpleDateFormat would take in the String and turn it into a Date once its able to parse it in. The parse would see that Tue would go into a ddd area in a SDF and May would go into a MMM if I had that in a simpleDateFormat. I dont. I have MM, and so its blowing up. I can do a M/d/yyyy in the input, so I end up giving it M, while askign for MM, and that still works.

Should I just scrap everything and go with JodaTime or is there a line or two that I'm missing?


This is how you obtain current date represented as a Java Date object:

Date date = new Date();

This is how you obtain current date as a formatted string:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy-kk:mm");
String formattedDateString = sdf.format(new Date());

You can then further parse it back into a Date:

Date date = sdf.parse(formattedDateString);

But there is no point in doing that because you already had the Date when you did the .format(...) call, only in your case you used


which typically gives the same result as

new Date()

If you want to parse a string into a Date then the string needs to match the format specified in SimpleDateFormat constructor. Date's toString() method that you are using returns a string in a specific format that does not match the format from your example, that's why you are getting the ParseException error.