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

如何在Kotlin的RecyclerView适配器中将API日期转为指定格式字符串

问题解决步骤

报错原因

getCreatedDate()未解析引用是Kotlin语法特性和字段匹配问题导致的:

  • Kotlin会自动将Java风格的getter/setter转换为属性调用,不需要加get/set前缀,直接访问属性即可
  • 可能ExpiryData类中不存在对应字段,或者字段名与API返回结果不匹配

另外你现有代码还有两处逻辑错误:

  1. 日期解析模式用了12小时制的hh,和API返回的24小时制HH不匹配,会导致下午时间解析出错
  2. onBindViewHolder中连续两次给holder.expiryDate1.text赋值,格式化后的结果会被后面的赋值直接覆盖

具体修复方案

  • 检查ExpiryData类定义,确认创建日期对应的字段名,如果是用JSON解析框架生成的类,确认字段的@SerializedName注解和API返回字段对应
  • 替换getCreatedDate()调用为Kotlin属性调用格式
  • 删除多余的赋值代码
  • 修正日期解析的模式字符串

修正后的代码示例

日期格式化函数

@Throws(ParseException::class)
private fun getFormattedDate(date: String): String? {
    val inputSdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
    val outputSdf = SimpleDateFormat("MMM dd", Locale.ENGLISH)
    val parseDate = inputSdf.parse(date) ?: return null
    return outputSdf.format(parseDate)
}

onBindViewHolder 代码

val thisModelResponse: ExpiryData = expiryList[position]
// 替换为你的实际字段名,不需要加get前缀
holder.expiryDate1.text = getFormattedDate(thisModelResponse.createdDate)
// 删掉原来的多余赋值代码:holder.expiryDate1.text = (expiryItem.expiryDate)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:45:04