How to get rid of StringIndexOutOfBoundsException while converting String to LocalDateTime

63 views Asked by At

While converting from String to LocalDateTime StringIndexOutOfBoundsException occured.

   String date = "2020-10-20 04:51:54";
   LocalDateTime dateTime = this.convertToLocalDate(date);
    public LocalDateTime convertToLocalDate(String datStr) {
        if ( datStr != null ) {
            datStr = (String) datStr.subSequence(0, datStr.lastIndexOf("+"));
        } else {
            return LocalDateTime.now();
        }

        return LocalDateTime.parse(datStr, dateFormatter);
    }

Getting Indexof as -1.

1

There are 1 answers

2
Marc H. On

Your string declared as date does not contain a plus sign.

The java documentation says following for the return value of String.lastIndex:

the index of the last occurrence of the specified substring, or -1 if there is no such occurrence.