Last active
July 21, 2019 12:45
-
-
Save alexfu/9cd35eb555cc1a02f6690222979334bb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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