3 Replies Latest reply: Aug 31, 2007 4:18 PM by 807605 RSS

    SimpleDateFormat.parse() causes Unparsable date exception

    807605
      I am using SimpleDateFormat to both format and parse date strings. The format is working properly, but parse results in the following exception:

      java.text.ParseException: Unparseable date: "2007-08-31T12:05:05.651-0700"
      at java.text.DateFormat.parse(Unknown Source)

      Here is my code:

      SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SZ");

      String dateTime = dateFormatter.format(new Date());
      Date test = dateFormatter.parse(dateTime);

      For testing purposes, I am formatting a date string, and then passing it right back into parse() and I get the exception.

      I am using jre1.5.0_10.

      Thank you for your help.

      -Karen
        • 1. Re: SimpleDateFormat.parse() causes Unparsable date exception
          807605
          import java.text.*;
          import java.util.*;
          
          public class ParseExample {
              public static void main(String[] args) throws ParseException {
                  SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S Z");
                  String dateTime = dateFormatter.format(new Date());
                  System.out.println(dateTime);
                  Date test = dateFormatter.parse(dateTime);
              }
          }
          \
          1. I put a space between S and Z -- running them together was confusing the parse method.
          2. kk is a weird format, so I used HH.
          • 2. Re: SimpleDateFormat.parse() causes Unparsable date exception
            807605
            You have specified the milliseconds (S) to have a minimum of 1 letter.
            From the API:
            Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

            If you specify it like this:
            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SSSZ");
            // or like this
            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.S Z");
            it will work.

            Message was edited by:
            dwg
            • 3. Re: SimpleDateFormat.parse() causes Unparsable date exception
              807605
              Thank you!

              Specifying it like this did the trick:

              SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SSSZ");

              I also noticed that the string I am really trying to parse is getting passed to me as "2007-08-29T13:12:46.607-07:00". Notice the colon in -07:00. I am expecting it to be -0700. Once that get fixed I will be good to go.

              Thanks again,
              -Karen