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

如何在Kotlin中使用android.text.format.DateFormat转换日期格式

解决Kotlin中DateFormat日期格式转换问题

现有代码问题

  • 调用DateFormat.getInstance()后直接调用format方法赋值给df变量,类型不匹配,format返回值是String类型,不是DateFormat对象
  • 不需要将crime.date转为String后再传入format方法,format方法可直接接收Date类型参数,多此一举的转换会导致格式化失败

解决方案

DateFormat的子类SimpleDateFormat支持自定义格式,完全可以满足你的转换需求,根据你的crime.date字段类型选择对应方案即可:

方案1:crime.date为Date类型(最优)

如果你的Crime类中date字段本身就是Date类型,直接构造目标格式的SimpleDateFormat格式化即可:

fun bind(crime: Crime){
    this.crime = crime
    titleTextView.text = this.crime.title
    // 指定Locale.US保证输出英文的星期、月份名称
    val targetFormat = SimpleDateFormat("EEE, MMM, dd, yyyy", Locale.US)
    // 直接传入Date对象即可,不需要转String
    dateTextView.text = targetFormat.format(this.crime.date)
    solvedImageView.visibility = if (crime.isSolved){
        View.VISIBLE
    }else{
        View.GONE
    }
}

方案2:crime.date为String类型

如果date字段是你给出的Sun Jul 25 00:00:00 GMT+09:00 2021格式的字符串,需要先解析为Date对象再格式化:

fun bind(crime: Crime){
    this.crime = crime
    titleTextView.text = this.crime.title
    // 构造解析用的格式对象,匹配输入字符串的结构
    val parseFormat = SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US)
    val date = parseFormat.parse(this.crime.date) // 实际使用请根据业务逻辑补充ParseException捕获逻辑
    // 构造目标格式对象
    val targetFormat = SimpleDateFormat("EEE, MMM, dd, yyyy", Locale.US)
    dateTextView.text = targetFormat.format(date)
    solvedImageView.visibility = if (crime.isSolved){
        View.VISIBLE
    }else{
        View.GONE
    }
}

用到的格式符说明

  • EEE:短格式星期名称,对应输出Sun
  • MMM:短格式月份名称,对应输出Jul
  • dd:两位的日期数值,对应输出25
  • yyyy:四位的年份数值,对应输出2021
  • 解析格式中的z:匹配时区标识,对应输入里的GMT+09:00

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 10:51:03