Format time to mm:ss.S with String.format in Kotlin/Java

Viewed 55

I want my time to be formated like: 03:04.9 (example)

This is what I have right now:

fun formatTime(data: Long): String {
    val seconds = ((data / 1000.0) % 60.0)
    val minutes = (TimeUnit.MILLISECONDS.toMinutes(data) % 60).toInt()
    return String.format(Locale.US, "%02d:%.1f", minutes, seconds)
}

It kind of works but doesn't make sure that the seconds value has two digits. This is how the output looks like when the seconds are under 10: 03:4.9

I think I'm so close but just can't get it right

1 Answers

As far as I know, its not possible to have control on leading zeros using string formatting. Alternately you can use DecimalFormat to achieve this.

fun formatTime(data: Long): String {
    val seconds = ((data / 1000.0) % 60.0)
    val minutes = (TimeUnit.MILLISECONDS.toMinutes(data) % 60).toInt()
    val formatSeconds = DecimalFormat("00.0").format(seconds)
    return String.format(Locale.US, "%02d:$formatSeconds", minutes)
}

This will provide outputs like,

03:14.9
03:04.9
03:00.9
03:00.0
03:04.0

Update:

Thanks Ole pointing it out in comment(Credits to him).
It is possible to with String.format() function itself, like below.

String.format(Locale.US, "%02d:%04.1f", minutes, seconds)

Also as Ole mentioned that, it is always better to use kotlin.time.Duration or java.time.Duration classes when you handle time.

Related