unhandled exception type ParseException

35k Views Asked by At

I'm using this part of code in my app :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
Date qdate = new GregorianCalendar(0,0,0).getTime();
try {
    qdate = sdf.parse(dt);
} catch (ParseException e) {
    e.printStackTrace();
}

but Eclipse throws an error saying :

Unhandled exception type ParseException

What is the problem here? Do u need me to post the whole code ? Thnx in advance !

3

There are 3 best solutions below

3
On BEST ANSWER

See below code

        String date = "Sat, 23 Jun 2012 00:00:00 +0000";
        try {
            SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
            SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
            date = df2.format(date));
        } catch (java.text.ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
0
On

java.time

It’s time to show the modern way of doing this. Use java.time, the modern Java date and time API.

    String dt = "2020-07-24T11:03:12Z";
    try {
        Instant i = Instant.parse(dt);
        System.out.println(i);
    } catch (DateTimeParseException dtpe) {
        System.err.println(dtpe);
    }

Output is:

2020-07-24T11:03:12Z

I am exploiting the fact that your format is ISO 8601 and the classes of java.time parse the most common variants of ISO 8601 as their default, that is, without any explicit formatter.

The exception comes into play if the string is not a valid ISO 8601 date and time in UTC. For example:

    String dt = "Not a valid date-time";

java.time.format.DateTimeParseException: Text 'Not a valid date-time' could not be parsed at index 0

The classes SimpleDateFormat and Date are poorly designed and long outdated, the former in particular notoriously troublesome. I recommend that nobody uses them anymore. The modern API is so much nicer to work with.

Links

1
On
Calendar c = Calendar.getInstance();

SimpleDateFormat df = new SimpleDateFormat("DD-MM-YYYY");

String Currentdatestr = df.format(c.getTime());

//get current date in String

Date date = df.parse(Currentdatestr);

//String to parse Date Format