I have below function which takes totalMinutes as an argument.
fun minutesToDaysHoursMinutes(totalMinutes: Double): String? {
var returnString = ""
try {
var minutes =0.0
if (totalMinutes > 6000) {
val days = totalMinutes / 1440
val remainingMins = totalMinutes - (1440 * days) // 310
var hours = remainingMins / 60
minutes = remainingMins - (hours * 60)
if (minutes >= 30) {
hours += 1
}
returnString = String.format("%01dd %01dh", days.toInt(), (hours + 1).toInt())
} else if (totalMinutes > 60) {
returnString =
String.format("%01dh %01dm", (totalMinutes / 60).toInt(), minutes.toInt())
} else {
returnString = String.format("%01dm", minutes.toInt())
}
} catch (e: Exception) {
Log.e(">> e1", ">>> e5")
e.printStackTrace()
}
return returnString
}
Calling function for 6050 minutes as :
tvTimeToCharge.text = minutesToDaysHoursMinutes(6050.0)
I am getting this output : 4d 0h
But The output should be as 4d 5h
Where I doing wrong?
The output requirement is as below :
6050 minutes is displayed as: 4d 5h (it is 4 days 4 hours and 50
minutes, 50 minutes we round to 1 hour)6090 minutes is displayed as: 4d 6h (it is 4 days 5 hours and 30
minutes, 30 minutes we round to 1 hour)6089 minutes is displayed as 4d 5h (it is 4 days 5 hours and 29
minutes, 29 minutes we round to 0 hours)
Let me know if any. Thanks.
2
Answers
6050.0 / 1440 is 4.2days, Math.floor(4.2) is 4 days.
6050.0 % 1440 is 290 minutes, 290 / 60 is 4.8 hours, Math.round(4.8) is 5 hours.
Instead of writing the whole logic yourself, more cleaner approach would be to use
Duration
class provided injava 8
time
API.For using
java 8
time
API inandroid
, you have to enablecoreLibraryDesugaring
in your module.In your app module’s
build.gradle
, addcoreLibraryDesugaringEnabled true
Now, you can use the
Duration
class to calculateday
andhour
duration like this