Java – Conversion of String to Date – Unparseable date: “03/26/2012”

ireportjasper-reportsjava

I'm experimenting on a Java Program that makes use of Jasper Reports. What started out as a (supposedly) simple "arrange the dates in descending order" task for the Report became more complex when I found out that the 'dates' were in String format, and thus, were being sorted, albeit in a wrong manner. Example:

  • 03/26/12
  • 03/26/12
  • 08/11/12
  • 08/26/12
  • 10/26/11

I can only guess that the 10/26/11 is placed on the bottom simply because of the 10 in front.

I've looked into the Jasper Report using iReport 3.0.0, and I've found the following:

  • The date in question (named: DTEEFFEC), under Fields, is set to String.
  • The textField is also set to String.

This doesn't produce any errors, it only makes it difficult, if not impossible, to arrange the 'dates' in descending order.

So I've done the following:

  • Left DTEEFFEC as is (String).
  • Changed the textField from Java.Lang.String to Java.Util.Date
  • Added the following to the New Field Expression:

    new SimpleDateFormat("MM-dd-yyyy").parse($F{DTEEFFEC}.toString())

I found out that bit of code after some research on my problem. A lot of the responses were along the lines of "it worked", but not so for me.

Caused by: java.text.ParseException: Unparseable date: "03/26/2012"

That is what the Java program returns. I've tried tinkering with both the field and the textField (alternating between either String or Date values), but it gives me other errors entirely.

Can I have some help on this?

Thanks.

Other information: I'm using iReports 3.0.0 to modify the JRXML file, and Eclipse for the Java Program. If the Referenced Libraries under Eclipse is to be believed, I'm using JasperReports 3.5.2. The entire thing runs on Windows 7.

Best Answer

Look at your code:

new SimpleDateFormat("MM-dd-yyyy").parse(...)

That's clearly expecting something of the form "MM-dd-yyyy" such as "03-26-2012".

Now look at your actual data: "03/26/2012". (Apparently, even though your earlier samples were two-digit years...)

That's got slashes, not dashes. So you need to change your pattern appropriately:

new SimpleDateFormat("MM/dd/yyyy").parse(...)