Java 8:DateTimeParseException

myn*_*EFF 12 java datetime datetime-format java-8

基本上,我试图将字符串解析为时间戳.

public static void main(String[] args) {
    System.out.println("Timestamp:" + DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").parse("20180301050630663"));
}
Run Code Online (Sandbox Code Playgroud)

我有一个例外说

Exception in thread "main" java.time.format.DateTimeParseException: Text '20180301050630663' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1947)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1849)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at Lob.main(Lob.java:41)
Run Code Online (Sandbox Code Playgroud)

然后我尝试这样做:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
LocalDateTime timestamp = LocalDateTime.parse("20180301050630663", fmt);
System.out.println("Timestamp:" + timestamp);
Run Code Online (Sandbox Code Playgroud)

并得到了同样的异常错误.

我在这做错了什么?理想情况下,我想将时间戳存储到变量中,并将其与我正在读取的另一个时间戳进行比较.我怎样才能做到这一点?

孙兴斌*_*孙兴斌 12

JDK8的一个错误已在JDK9中解决:

https://bugs.java.com/view_bug.do?bug_id=JDK-8031085

更新

正如User @Aaron在评论中所说,您可以使用错误跟踪器IMO中包含的解决方法:

public static void main(String[] args) {
    DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern("yyyyMMddHHmmss").appendValue(ChronoField.MILLI_OF_SECOND, 3).toFormatter();
    System.out.println("Timestamp:" + dtf.parse("20180301050630663"));
}
Run Code Online (Sandbox Code Playgroud)