英文:
How to get rid of StringIndexOutOfBoundsException while converting String to LocalDateTime
问题
在从String转换为LocalDateTime时发生了StringIndexOutOfBoundsException。
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);
}
获取的Indexof值为-1。
英文:
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
得分: 1
你声明为日期的字符串中没有包含加号。
Java文档对于String.lastIndex的返回值有以下说明:
指定子字符串最后一次出现的索引,如果没有出现则返回-1。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论