Search code examples
javadatesimpledateformatdatetime-parsingunparseable

Java: Date parsing, why do I get an error


    Date date = new Date();
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ");//2018-02-05T18:00:51.001+0000
    String text = dateFormat.format(date);

    Date test = dateFormat.parse(text);

The first three lines work fine. When I try to parse the string into a date again I get an error. How can I solve this?

The error looks like this:

Caused by: java.text.ParseException: Unparseable date: "2018-02-07T15:32:13.214+0100"
    at java.text.DateFormat.parse(DateFormat.java:366) ~[na:1.8.0_151]
    at TimeRange.parseDateFromIsoString(TimeRange.java:33) ~[classes/:na]

Solution

  •     Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");//2018-02-05T18:00:51.001+0000
        String text = dateFormat.format(date);
    
        try {
            Date test = dateFormat.parse(text);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    

    worked for me. With "SSSZ" instead of "SZ" at the end of the pattern.