如何在 Java 8 中解析不包含标点符号的 ISO-8601 格式字符串?

Pat*_*ogt 6 java localdate

如何将以下字符串解析为LocalDateTime-Object?

20200203092315000000

我总是收到以下异常,但我不明白:

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)
Run Code Online (Sandbox Code Playgroud)

我的应用程序代码如下所示:

LocalDateTime ldt = LocalDateTime.parse("20200203092315000000", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSSSS"));
Run Code Online (Sandbox Code Playgroud)

Mar*_*bel 5

看起来像一个已知问题...

bug_id=JDK-8031085 bug_id=JDK-8138676

解决方法:

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

或者

客户提交的解决方法:使用以下格式(注意“.”):“yyyyMMddHHmmss.SSS”

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

或者使用 jodatime 库