0

I have the following DateTimeFormatter code

DateTimeFormatter sysDateFmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

And an example of the timestamp would be 2018-09-04 09:16:11.305. The milliseconds have 3 digits. And the following code to parse the timestamp would just work fine.

LocalTime.parse("2018-09-04 09:16:11.305", sysDateFmt)

However, sometimes the millisecond part of the timestamp I encountered only have 2 digits, i.e. 2018-09-12 17:33:30.42. Then this is where I come across the error below.

Exception in thread "main" java.time.format.DateTimeParseException: Text '2018-09-12 17:33:30.42' could not be parsed at index 20

What is the efficient solution to overcome this problem?

3
  • You might to need to use a more lenient approach - for example Commented Dec 29, 2018 at 7:16
  • Maybe this could help Commented Dec 29, 2018 at 7:22
  • Should the time be equivalent to 2018-09-12 17:33:30.420 or 2018-09-12 17:33:30.042? Commented Dec 29, 2018 at 7:56

1 Answer 1

0

you can get the length of date

    String a = "2018-09-04 09:16:11.305"; //length = 23
    String b = "2018-09-04 09:16:11.30";  //length = 22

then

    String date = null;
    DateTimeFormatter sysDateFmt23 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    DateTimeFormatter sysDateFmt22 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS");

    if (date.length() == 23){
        LocalTime.parse(date, sysDateFmt23);
    } else if (date.length() == 22){
        LocalTime.parse(date, sysDateFmt22);
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.