Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.text.ParseException: Unparseable date:

Tags:

java

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();
        }
    }

}
like image 367
Pawan Avatar asked Nov 16 '11 14:11

Pawan


People also ask

What is unparseable date error in Java?

The error java.text.ParseException: Unparseable date usually occurs while using the SimpleDateFormat class in Java. This class is used to format the date in Java. Most of the time, the error java.text.ParseException: Unparseable date occurs when we try to convert the string date into another desired date format.

What is a checked exception in Java?

This is a checked exception an it can occur when you fail to parse a String that is ought to have a special format. One very significant example on that is when you are trying to parse a String to a Date Object. As you might know, that string should have a specified format.

Why can't I convert date time to text in Java?

You are using troublesome old date-time classes that were supplanted years ago by the java.time classes. Instead a format such as yours, use ISO 8601 standard formats for exchanging date-time values as text. The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings.


2 Answers

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");
like image 97
Chris Avatar answered Oct 21 '22 08:10

Chris


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.)

like image 34
Jon Skeet Avatar answered Oct 21 '22 07:10

Jon Skeet