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

Android(Kotlin):RecyclerView自定义时间格式UI更新问题

新闻应用界面

你当前的时间格式逻辑存在几个问题:

  • 时间差计算顺序错误:Duration.between(currentTimeInHours, newsTimeInHours) 计算的是当前时间到新闻发布时间的间隔,由于新闻时间早于当前时间,结果为负数,你通过substring(1)截取数字属于临时 workaround,正确的做法是反过来传参,计算新闻发布时间到当前时间的差值
  • 小时数单复数未处理:无论小时数是多少都固定显示"hour ago",当小时数大于1时应该显示"hours ago"
  • 冗余的字符串截取操作:只要参数顺序正确,时间差值就是正数,完全不需要处理负号

替换为以下修正后的代码即可解决问题:

val currentTime = Instant.now().atZone(ZoneId.of("Asia/Kolkata"))
val newsTime = Instant.parse(time).atZone(ZoneId.of("Asia/Kolkata"))
val timeDifference = Duration.between(newsTime, currentTime)

val timeAgoText = if (timeDifference.toMinutes() < 60) {
    "${timeDifference.toMinutes()} minutes ago"
} else {
    val hours = timeDifference.toHours()
    "$hours ${if (hours > 1) "hours" else "hour"} ago"
}

holder.tvPublishedAt.text = timeAgoText

额外优化建议:

  • 将时区Asia/Kolkata抽取为适配器内的常量,避免重复编写,例如:private val INDIA_TIME_ZONE = ZoneId.of("Asia/Kolkata")
  • 对Instant.parse(time)添加try-catch异常捕获,防止接口返回非法时间格式导致应用崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:50:19