mepi0011
mepi0011

Reputation: 55

Correct way to get the duration between a time strings and current time in Kotlin

What is the correct and easiest way to get the duration between a time string and actual time in Kotlin?

I have following time strings (timeStr): "18:00:00" At the end I like to have a string like this: "x hours and y minutes to ..."

My current solution:

val diff: Long = (LocalTime.parse(timeStr).toSecondOfDay() - LocalTime.now().toSecondOfDay()).toLong()
val duration: LocalTime = LocalTime.ofSecondOfDay(diff)
outStr = duration.hour + "hours and " + duration.minute + " minutes to ..."

I am aware that the solution is error prone, so I am looking for a clean solution. I have only recently started using Kotlin and am not yet familiar with the possibilities.

Upvotes: 4

Views: 1464

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79550

I recommend you use java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenience methods were introduced.

Demo:

public class Main {
    public static void main(String[] args) {
        Duration duration = Duration.between(LocalTime.now(), LocalTime.parse("18:00:00"));
        // Default format
        System.out.println(duration);

        // Custom format
        // ####################################Java-8####################################
        String formattedDuration = String.format("%d hour(s) and %d minute(s)", duration.toHours(),
                duration.toMinutes() % 60);
        System.out.println(formattedDuration);
        // ##############################################################################

        // ####################################Java-9####################################
        formattedDuration = String.format("%d hour(s) and %d minute(s)", duration.toHoursPart(),
                duration.toMinutesPart());
        System.out.println(formattedDuration);
        // ##############################################################################
    }
}

Output from a sample run:

PT47M23.239687S
0 hour(s) and 47 minute(s)
0 hour(s) and 47 minute(s)

Online Demo

Learn about the modern date-time API from Trail: Date Time.

Upvotes: 5

ProjectDelta
ProjectDelta

Reputation: 888

As "Anonymous" commented, you can use the Duration classes for this:

fun getDuration(timeStr: String): String {
    val time = LocalTime.parse(timeStr)
    val now = LocalTime.now()
    val duration = Duration.between(now, time)
    val hours = duration.toHours()
    val minutes = duration.minusHours(hours).toMinutes()
    return if (hours == 0L) {
        "$minutes minutes to ..."
    } else if (minutes == 0L) {
        "$hours hours to ..."
    } else {
        "$hours hours and $minutes minutes to ..."
    }
}

Upvotes: 2

Related Questions