8

Could anybody please tell me why i am getting java.text.ParseException: Unparseable date in the following code:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


public class Testdate {
    public static void main(String args[])
    {
        String text = "2011-11-19T00:00:00.000-05:00";
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        try {
            Date parsed = sdf.parse(text.trim());
            System.out.println(parsed);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}
COD3BOY
  • 11,964
  • 1
  • 38
  • 56
Pawan
  • 31,545
  • 102
  • 256
  • 434

2 Answers2

8

Its because of the colon in your timezone. Remove it and it will work:

String text = "2011-11-19T00:00:00.000-0500";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Chris
  • 8,031
  • 10
  • 41
  • 67
  • you used a different String , but the actual String is "2011-11-19T00:00:00.000-05:00"; , I want the colon also – Pawan Nov 16 '11 at 14:44
  • was just the explanation why it fails, and one way how to work around it. – Chris Nov 16 '11 at 14:46
  • I would investigate why you get a date, which is not RFC conform.. you can workaround it by just removing the last colon, but this is obviously a bad work around. – Chris Nov 16 '11 at 14:49
  • Here's how I removed the colon: String dateStr = "2013-06-25T16:09:41.276-05:00"; Matcher m = Pattern.compile("(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}-)(\\d{2}:\\d{2})").matcher(dateStr); if (m.matches()) { dateStr = m.group(1) + m.group(2).replace(":", ""); } Date date = new SimpleDateFormat("yyyy-M-d'T'HH:mm:ss.SSSZ").parse(dateStr); System.out.printf("Date = '%s'", date); – starryknight64 Jun 28 '13 at 21:56
5

Because the Z part of SimpleDateFormat's pattern support doesn't handle offsets with colons in.

I suggest you use Joda Time instead, using ISODateFormat.dateTime() to get an appropriate formatter.

(See this similar-but-not-quite-the-same-question from earlier today for more information.)

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194