如何在将字符串转换为LocalDateTime时解决StringIndexOutOfBoundsException错误。

huangapple go评论62阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年10月21日 01:00:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64449946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定