Unhandled Exception Type Parseexception
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 { qda
Solution 1:
See below code
Stringdate="Sat, 23 Jun 2012 00:00:00 +0000";
try {
SimpleDateFormatformat=newSimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
SimpleDateFormatdf2=newSimpleDateFormat("dd/MM/yy");
date = df2.format(date));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Solution 2:
java.time
It’s time to show the modern way of doing this. Use java.time, the modern Java date and time API.
Stringdt="2020-07-24T11:03:12Z";
try {
Instanti= 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:
Stringdt="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
- Oracle tutorial: Date Time explaining how to use java.time.
- Wikipedia article: ISO 8601
Solution 3:
Calendarc= Calendar.getInstance();
SimpleDateFormatdf=newSimpleDateFormat("DD-MM-YYYY");
StringCurrentdatestr= df.format(c.getTime());
//get current date in StringDatedate= df.parse(Currentdatestr);
//String to parse Date Format
Post a Comment for "Unhandled Exception Type Parseexception"