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

Kotlin中用SimpleDateFormat转换日期字符串14 Sep 2021报错

解决日期字符串解析失败问题

问题原因

SimpleDateFormat默认依赖当前系统的Locale,若系统Locale不是英文,就无法识别Sep这类英文月份缩写,进而导致解析失败。

解决方案1:为SimpleDateFormat指定英文Locale

修改代码时,在创建SimpleDateFormat实例时传入Locale.ENGLISH,确保能正确解析英文月份缩写:

private fun convertToDayAndMonth(date: String): String {
    val inputFormat = SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH)
    val dateObj: Date = inputFormat.parse(date)!!
    val outputFormat = SimpleDateFormat("d MMM", Locale.ENGLISH)
    return outputFormat.format(dateObj)
}

注意:!!可能引发空指针异常,若输入日期格式不合法,建议替换为更安全的异常处理逻辑:

private fun convertToDayAndMonth(date: String): String? {
    return runCatching {
        val inputFormat = SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH)
        val dateObj = inputFormat.parse(date) ?: return null
        val outputFormat = SimpleDateFormat("d MMM", Locale.ENGLISH)
        outputFormat.format(dateObj)
    }.getOrNull()
}

解决方案2:使用Java 8+新日期API(推荐)

SimpleDateFormat存在线程不安全问题,Java 8及以上版本推荐使用java.time包下的API,安全性和功能性更优:

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale

private fun convertToDayAndMonth(date: String): String? {
    val inputFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH)
    return runCatching {
        val localDate = LocalDate.parse(date, inputFormatter)
        val outputFormatter = DateTimeFormatter.ofPattern("d MMM", Locale.ENGLISH)
        localDate.format(outputFormatter)
    }.getOrNull()
}

内容的提问来源于stack exchange,提问作者Dion Ng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 01:09:29