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?

mynameisJEFF
  • 4,073
  • 9
  • 50
  • 96
  • You might to need to use a more lenient approach - [for example](https://stackoverflow.com/questions/32962417/lenient-java-8-date-parsing) – MadProgrammer Dec 29 '18 at 07:16
  • [Maybe this could help](https://stackoverflow.com/questions/44950633/how-to-create-datetimeformatter-with-optional-seconds-arguments) – Nicholas K Dec 29 '18 at 07:22
  • Should the time be equivalent to 2018-09-12 17:33:30.420 or 2018-09-12 17:33:30.042? – Kody Puebla Dec 29 '18 at 07:56

1 Answers1

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);
    }
wl.GIG
  • 306
  • 1
  • 2
  • 13