首页 > 解决方案 > 如何转换 ISO 时间以显示几小时前在 android studio 中发布的内容?

问题描述

我正在使用我想要转换的 ISO 格式,然后显示该项目是多少小时前获得的。我已经为此编写了代码,但是由于某种原因返回结果不正确。例如,如果时间是一分钟前,则表示三小时前!我的问题是格式化不起作用 ISO 转换工作但格式错误!

这是我重新格式化我得到的时间的课程:

class ReformatTime {

@SuppressLint("SimpleDateFormat")
fun convertISOTime(time: String): String {
    val inputPattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"
    val inputFormat = SimpleDateFormat(inputPattern)
    return getTimeAgo(inputFormat.parse(time).time)
}

companion object {
    private const val SECOND_MILLIS = 1000
    private const val MINUTE_MILLIS = 60 * SECOND_MILLIS
    private const val HOUR_MILLIS = 60 * MINUTE_MILLIS
    private const val DAY_MILLIS = 24 * HOUR_MILLIS
}

private fun getTimeAgo(time: Long): String {
    var time = time

    if (time < 1000000000000L) {
        // if timestamp given in seconds, convert to millis
        time *= 1000
    }

    val now = System.currentTimeMillis()
    if (time > now || time <= 0) return ""

    val diff = now - time
    return when {
        diff < MINUTE_MILLIS -> "just now"
        diff < 2 * MINUTE_MILLIS -> "a minute ago" 
        diff < 50 * MINUTE_MILLIS -> "${diff / MINUTE_MILLIS}  minutes ago"
        diff < 90 * MINUTE_MILLIS -> "an hour ago"
        diff < 24 * HOUR_MILLIS -> "${diff / HOUR_MILLIS} hours ago"
        diff < 48 * HOUR_MILLIS -> "yesterday"
        else -> "${diff / DAY_MILLIS} days ago"
    }
}}

标签: androidtimekotlin

解决方案


推荐阅读