【问题标题】:How to get rid of StringIndexOutOfBoundsException while converting String to LocalDateTime [closed]如何在将 String 转换为 LocalDateTime 时摆脱 StringIndexOutOfBoundsException [关闭]
【发布时间】:2020-10-20 17:00:00
【问题描述】:

从 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。

【问题讨论】:

标签: java spring-boot date java-8 localdatetime


【解决方案1】:

您声明为日期的字符串不包含加号。

Java 文档说明 String.lastIndex 的返回值如下:

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

【讨论】:

  • 我从 db 获取这个字符串。如何将其转换为 LocalDateTime
  • 感谢您的帮助。此问题是由拼写错误引起的。
猜你喜欢
  • 1970-01-01
  • 2014-12-04
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
  • 2014-10-22
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多