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"));
}
Looks like it's a bug. That code works in Java 10 (and 9, it seems).
You can go around the issue using java.text.SimpleDateFormat:
new java.text.SimpleDateFormat('yyyyMMddHHmmssSSS').
parse("20180301050630663")
Which works just fine (Thu Mar 01 05:06:30 SAST 2018
is the output in my TZ):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With