Currently, I went on tinkering with the features of one of my pet projects. I decided to include the feature to block a user from doing certain action/s and display a banner to show the cooldown period.
Eg.
Given: User is blocked for doing certain action/s from November 19, 2019 2:00:00 AM (1574128800) up to November 21, 2019 6:32:00 PM (1574361120).
Output: 2 days 16 hours 32 minutes
This is the method I have right now. Unfortunately, it only works on Android API >= 26.
/**
* If using for Android, `Duration` requires API > 26
* @param start Epoch time in milliseconds
* @param end Epoch time in milliseconds
*/
fun getReadableBetween(start: Long, end: Long): String {
val startDate = Date(start)
val endDate = Date(end)
var duration = Duration.between(startDate.toInstant(), endDate.toInstant())
val days = duration.toDays()
duration = duration.minusDays(days)
val hours = duration.toHours()
duration = duration.minusHours(hours)
val minutes = duration.toMinutes()
val stringBuilder = StringBuilder()
if (days != 0L) {
stringBuilder.append(days)
if (days == 1L) {
stringBuilder.append(" day ")
} else {
stringBuilder.append(" days ")
}
}
if (hours != 0L) {
stringBuilder.append(hours)
if (hours == 1L) {
stringBuilder.append(" hour ")
} else {
stringBuilder.append(" hours ")
}
}
if (minutes != 0L) {
stringBuilder.append(minutes)
if (minutes == 1L) {
stringBuilder.append(" minute.")
} else {
stringBuilder.append(" minutes.")
}
}
println("Breakdown:")
println("Days: $days")
println("Hours: $hours")
println("Minutes: $minutes")
return stringBuilder.toString()
}
As much as I would like to use 3rd party libraries, I'd like to get my hands dirty using the fundamentals of date and time APIs available out of the box.
PS. Before linking this to other SO posts, please consider the scenario.