Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse an ISO-8601 formatted string that contains no punctuation in Java 8?

Tags:

java

localdate

How could I parse the following String to a LocalDateTime-Object?

20200203092315000000

I always get the following exception but I didn't understand it:

java.time.format.DateTimeParseException: Text '20200203092315000000' could not be parsed at index 0

    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at de.x.struct.type.LocalDateTimeStructField.setBytesValue(LocalDateTimeStructField.java:44)
    at de.x.struct.Struct.bytesToStruct(Struct.java:110)
    at de.x.struct.StructTest.testStringToStruct(StructTest.java:60)

My application code looks like:

LocalDateTime ldt = LocalDateTime.parse("20200203092315000000", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSSSS"));
like image 233
Patrick Vogt Avatar asked Jan 03 '20 10:01

Patrick Vogt


1 Answers

looks like a known issue...

bug_id=JDK-8031085 bug_id=JDK-8138676

Workaround:

DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern("yyyyMMddHHmmss").appendValue(ChronoField.MILLI_OF_SECOND, 3).toFormatter()

or

CUSTOMER SUBMITTED WORKAROUND : use the following format (mind the '.'): "yyyyMMddHHmmss.SSS"

LocalDateTime.parse("20150910121314987", DateTimeFormatter.ofPattern("yyyyMMddHHmmss.SSS"))

or alternatively use jodatime library

like image 200
Marc Stroebel Avatar answered Nov 15 '22 14:11

Marc Stroebel