13

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 ?

0

2 Answers 2

15

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"));
}
Sign up to request clarification or add additional context in comments.

5 Comments

As a workaround, if applicable, adding any separator works: DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss-SSS").parse("2018-03-01-05-06-30-663")
@HBo That's right.
Better use the workaround that is included in the bug tracker IMO : DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern("yyyyMMddHHmmss").appendValue(ChronoField.MILLI_OF_SECOND, 3).toFormatter()
@Aaron dude, you killed my vibe... But you're totally right about it!
@HBo sorry about your vibe, may it rest in peace ;)
1

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):

1 Comment

Works in Java 9 too. Timestamp:{},ISO resolved to 2018-03-01T05:06:30.663

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.