How to get rid of StringIndexOutOfBoundsException while converting String to LocalDateTime

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 answer

  • answered 2020-10-20 17:14 Marc H.

    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.