我正在使用要转换的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"
}
}}