DateTimeFormatter.format()抛出ArrayIndexOutOfBoundsException异常求助
问题分析与解决方案
核心原因
你遇到的ArrayIndexOutOfBoundsException是因为给格式化LocalDate的DateTimeFormatter设置了时区,而LocalDate本身不包含时区信息。在部分Android版本的java.time兼容实现(即日志里的j$.time)中,这种组合会触发底层数组越界的bug——当Formatter绑定了时区,但要格式化的是无时区的日期类型时,内部处理逻辑出现索引错误。
你的代码里调用了.withZone(ZoneId.systemDefault()),这是多余且有害的,因为LocalDate不需要时区就能完成格式化。
修复方案
直接移除.withZone(ZoneId.systemDefault())即可,修改后的工具函数如下:
fun dateTimeFormatterOfBestDateTimePattern( pattern: String, locale: Locale = Locale.getDefault() ): DateTimeFormatter { val datePattern = android.text.format.DateFormat.getBestDateTimePattern(locale, pattern) return DateTimeFormatter.ofPattern(datePattern) .withLocale(locale) }
额外说明
- 你本地设备没崩溃是因为不同Android版本的
java.time实现存在差异,旧版本或者特定厂商的ROM里更容易触发这个bug。 - 如果后续需要处理带时区的日期时间(比如
ZonedDateTime),再添加.withZone()调用即可,针对LocalDate场景完全不需要时区配置。
内容的提问来源于stack exchange,提问作者okycelt
相关产品推荐
相关产品推荐

