三星Galaxy S21 FE(Android13)上ThreeTen LocalDateTime解析崩溃求助
问题排查与解决方案
核心原因
报错指向索引19(对应字符串里的AM位置),说明AM/PM标记解析失败。三星Galaxy S21 FE的系统Locale设置存在特殊情况,即便你尝试添加Locale,可能是添加方式有误,或者手动替换BST的操作不够可靠。
修复方案
方案1:用Builder构建解析规则(推荐)
手动替换BST容易出现遗漏或格式变动问题,建议用DateTimeFormatterBuilder直接兼容带时区的字符串,同时强制指定英文Locale确保月份缩写、AM/PM的识别:
private fun toLocalDate(date: String?): LocalDateTime? { return try { val formatter = DateTimeFormatterBuilder() .appendPattern("dd-MMM-yy hh:mm:ss a") .appendLiteral(" ") .appendZoneText(TextStyle.SHORT) // 匹配BST这类时区缩写 .toFormatter(Locale.ENGLISH) // 强制英文Locale,避免系统Locale干扰 ZonedDateTime.parse(date, formatter).toLocalDateTime() } catch (e: Exception) { e.printStackTrace() null } }
方案2:优化手动移除时区的逻辑
如果坚持手动处理时区字符串,改用正则匹配末尾时区代码,并确保DateTimeFormatter绑定英文Locale:
private fun toLocalDate(date: String?): LocalDateTime? { return try { val inputFormat = DateTimeFormatter.ofPattern("dd-MMM-yy hh:mm:ss a", Locale.ENGLISH) // 用正则匹配末尾的3位大写时区代码,兼容BST、GMT等多种情况 val formattedDate = date?.replace(Regex("\\s+[A-Z]{3}$"), "") formattedDate?.let { LocalDateTime.parse(it, inputFormat) } } catch (e: Exception) { e.printStackTrace() null } }
关键说明
- 三星部分设备系统Locale默认非英文,或对AM/PM的本地化处理有差异,强制指定
Locale.ENGLISH是解决解析失败的核心。 - 正则替换比固定字符串替换更通用,能适配不同时区缩写的情况。
- 使用
DateTimeFormatterBuilder无需修改原字符串,直接兼容带时区的格式,降低出错概率。
内容的提问来源于stack exchange,提问作者Sourav
相关产品推荐
相关产品推荐

