Java 8 bug : java.time.format.DateTimeParseException

  • A+
Category:Languages
 Basically, I am trying to parse a string to a timestamp.

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

I got an exception saying that


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)

Then I tried doing this:


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

And got the same exception error too.

What have I done wrong here? Ideally, I want to store the timestamp to a variable and compare it with another timestamp that I am reading in . How can I achieve that ?


A bug of JDK8 and has been resolved in JDK9:

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

Update

As User @Aaron said in comment, you can use the workaround that is included in the bug tracker 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"));
}

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: