Search code examples
javaandroidgregorian-calendarparseexception

String from\to GregorianCalendar cause java.text.ParseException: Unparseable date


I need to convert a GregorianCalendar to a String and reconvert this string to a GregorianCalendar again

I use this to convert the String in a GregorianCalendar

        DateFormat format = new SimpleDateFormat();
        Date date = null;
        try {
            date = format.parse(dateS);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);

Unfortunately when I invoke the second method I get this error

java.text.ParseException: Unparseable date: "11 apr 2014 21:48:02" (at offset 2)

at this line

date = format.parse(dateS);

Solution

  • You need to instantiate your SimpleDateFormat object with the pattern it will use to parse the date String. In your case:

    DateFormat format = new SimpleDateFormat("d MMM yyyy HH:mm:ss");
    

    A table of the acceptable pattern symbols can be found in the docs for SimpleDateFormat