'Java ParseException Unparseable date when date string is UTC+13:00 timezone
I am getting weird error which I can't get around easily. This is my code
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.[S][SS][SSS][SSSS][SSSSS][SSSSSS][SSSSSSS][SSSSSSSS][SSSSSSSSS]X");
df.setTimeZone(TimeZone.getDefault());
Date issued = df.parse(this.dateAndTimeOfIssue);
I am getting exception java.text.ParseException: Unparseable date: "2018-02-13T00:00:51.045+13:00"
Does anyone knows what is causing error?
Solution 1:[1]
tl;dr
Date.from(
OffsetDateTime
.parse( "2018-02-13T00:00:51.045+13:00" )
.toInstant()
)
Details
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Avoid Date/Calendar.
For a date with time of day as seen with a particular offset, use OffsetDateTime class.
Your input text complies with the standard ISO 8601 format used by default in the java.time classes. So no need to specify a formatting pattern.
OffsetDateTime.parse( "2018-02-13T00:00:51.045+13:00" )
If you must use the legacy classes to interoperate with old code not yet updated for java.time, you can convert to and fro. Use the new conversion methods added to the old classes.
java.util.Date d = Date.from( myOffsetDateTime.toInstant() ) ;
All this has been covered many many times already on Stack Overflow. Search to learn more. And see the tutorial provided by Oracle Corp free of cost.
Solution 2:[2]
Your issue is that SimpleDateFormat does not support the optional sections - that is, the enclosure of parts of the format in [ ] characters. You need to either
- abandon the use of the optional sections,
- write your own
DateFormatimplementation, - switch to the more modern classes in the
java.timepackage.
The third option is usually the best - the java.time package has been around for many years now, and the DateTimeFormatter class does indeed support the [ ] notation. But if you have to deal with legacy date and time classes, you might be best to write your own DateFormat.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Dawood ibn Kareem |
