Home > Software design >  Issue in forming desired output with Day, Hour & Minute in Kotlin - Android
Issue in forming desired output with Day, Hour & Minute in Kotlin - Android

Time:12-08

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("dd dh", days.toInt(), (hours   1).toInt())
        } else if (totalMinutes > 60) {
            returnString =
                String.format("dh dm", (totalMinutes / 60).toInt(), minutes.toInt())
        } else {
            returnString = String.format("dm", 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.

CodePudding user response:

val days = Math.floor(totalMinutes / 1440)
var hours = Math.round((totalMinutes % 1440) / 60)

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.

CodePudding user response:

Instead of writing the whole logic yourself, more cleaner approach would be to use Duration class provided in java 8 time API.

For using java 8 time API in android, you have to enable coreLibraryDesugaring in your module.

In your app module's build.gradle, add coreLibraryDesugaringEnabled true

compileOptions {
        coreLibraryDesugaringEnabled true
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
}

Now, you can use the Duration class to calculate day and hour duration like this

val days = Duration.ofMinutes(totalMinutes.toLong()).toDays()
val hours = Duration.ofMinutes(totalMinutes.toLong()).toHoursPart()   
            (Duration.ofMinutes(totalMinutes.toLong()).toMinutesPart() / 60.0).roundToInt()
    
  • Related