0

I am getting a time with an ISO format that I want to convert and then show how many hours ago that item was gotten. I have written the code for that, but the result is not correct when it's returned for some reason. For example, if the time is a minute ago, it says three hours ago! My problem is that the formatting does not work the ISO conversion works but the formatting is wrong!

This is my class for reformatting the time that I am getting:

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"
    }
}}
medusa
  • 46
  • 8

0 Answers0