Created
October 3, 2019 09:46
-
-
Save pfieffer/7b4daab3c6a650552e078a29c6d475dd to your computer and use it in GitHub Desktop.
Get time in user friendly format. Extension function on top of Long class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun Long.getFriendlyTime(): String { | |
val dateTime = Date(this * 1000) | |
val sb = StringBuffer() | |
val current = Calendar.getInstance().time | |
var diffInSeconds = ((current.time - dateTime.time) / 1000).toInt() | |
val sec = if (diffInSeconds >= 60) (diffInSeconds % 60) else diffInSeconds | |
diffInSeconds /= 60 | |
val min = if (diffInSeconds >= 60) (diffInSeconds % 60) else diffInSeconds | |
diffInSeconds /= 60 | |
val hrs = if (diffInSeconds >= 24) (diffInSeconds % 24) else diffInSeconds | |
diffInSeconds /= 24 | |
val days = if (diffInSeconds >= 30) (diffInSeconds % 30) else diffInSeconds | |
diffInSeconds /= 30 | |
val months = if (diffInSeconds >= 12) (diffInSeconds % 12) else diffInSeconds | |
diffInSeconds /= 12 | |
val years = diffInSeconds | |
if (years > 0) { | |
if (years == 1) { | |
sb.append("a year") | |
} else { | |
sb.append("$years years") | |
} | |
if (years <= 6 && months > 0) { | |
if (months == 1) { | |
sb.append(" and a month") | |
} else { | |
sb.append(" and $months months") | |
} | |
} | |
} else if (months > 0) { | |
if (months == 1) { | |
sb.append("a month") | |
} else { | |
sb.append("$months months") | |
} | |
if (months <= 6 && days > 0) { | |
if (days == 1) { | |
sb.append(" and a day") | |
} else { | |
sb.append(" and $days days") | |
} | |
} | |
} else if (days > 0) { | |
if (days == 1) { | |
sb.append("a day") | |
} else { | |
sb.append("$days days") | |
} | |
if (days <= 3 && hrs > 0) { | |
if (hrs == 1) { | |
sb.append(" and an hour") | |
} else { | |
sb.append(" and $hrs hours") | |
} | |
} | |
} else if (hrs > 0) { | |
if (hrs == 1) { | |
sb.append("an hour") | |
} else { | |
sb.append("$hrs hours") | |
} | |
if (min > 1) { | |
sb.append(" and $min minutes") | |
} | |
} else if (min > 0) { | |
if (min == 1) { | |
sb.append("a minute") | |
} else { | |
sb.append("$min minutes") | |
} | |
if (sec > 1) { | |
sb.append(" and $sec seconds") | |
} | |
} else { | |
if (sec <= 1) { | |
sb.append("about a second") | |
} else { | |
sb.append("about $sec seconds") | |
} | |
} | |
sb.append(" ago") | |
return sb.toString() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment