Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
val units = listOf(
ChronoUnit.MILLENNIA,
ChronoUnit.CENTURIES,
ChronoUnit.DECADES,
ChronoUnit.YEARS,
ChronoUnit.MONTHS,
ChronoUnit.WEEKS,
ChronoUnit.DAYS,
ChronoUnit.HOURS,
ChronoUnit.MINUTES,
ChronoUnit.SECONDS
)
fun main() {
println(durationToHumanReadableString((Duration.ofHours(12) + Duration.ofMinutes(30)).toMillis())) // 12 Hours 30 Minutes
println(durationToHumanReadableString(Duration.ofDays(1000000).toMillis())) // 2 Millennia 7 Centuries 3 Decades 7 Years 10 Months 3 Weeks 5 Days 21 Hours 48 Minutes 36 Seconds
println(durationToHumanReadableString((Duration.ofDays(365) + Duration.ofDays(183)).toMillis())) // 1 Years 6 Months 3 Hours 16 Minutes 12 Seconds
}
fun durationToHumanReadableString(durationInMillis: Long): String {
units.forEach { unit ->
if (durationInMillis >= unit.duration.toMillis()) {
val durationValue = durationInMillis / unit.duration.toMillis()
val remainder = durationInMillis.rem(unit.duration.toMillis())
val remainderString = if (remainder != 0L) {
" ${durationToHumanReadableString(remainder)}"
} else {
""
}
return "$durationValue $unit$remainderString"
}
}
return ""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment