android - 如何转换 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"
}
}}
解决方案
推荐阅读
- javascript - PHP preg_replace 转换为 Javascript 替换
- c# - 如何从 specflow 挂钩访问另一个类的方法
- reactjs - 如何从 React Virtualized 中的列表项折叠子项
- python - python:将特定索引处的行从一个数据帧插入到另一个数据帧
- python - Python:可用于折叠/折叠多行代码的无害括号?
- docker - 为什么不能在个人修改的 CentOS docker 映像中运行 cron 作业?
- c++ - C++公历年份显示算法
- flutter - 我如何包装小部件列表?
- python - 如何在用户输入的位置找到按钮并在pygame中更改它的颜色?
- php - 提交时无法获取引导下拉列表的值