You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 17:44:52