Add a duration formatter.

This commit is contained in:
Benoit Marty
2024-11-27 11:40:14 +01:00
committed by Benoit Marty
parent 14d42010fb
commit fdb1123127
3 changed files with 88 additions and 0 deletions

View File

@@ -11,4 +11,9 @@ plugins {
android {
namespace = "io.element.android.libraries.dateformatter.api"
dependencies {
testImplementation(libs.test.junit)
testImplementation(libs.test.truth)
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2024 New Vector Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only
* Please see LICENSE in the repository root for full details.
*/
package io.element.android.libraries.dateformatter.api
import java.util.Locale
/**
* Convert milliseconds to human readable duration.
* Hours in 1 digit or more.
* Minutes in 2 digits when hours are available.
* Seconds always on 2 digits.
* Example:
* - when the duration is longer than 1 hour:
* - "10:23:34"
* - "1:23:34"
* - "1:03:04"
* - when the duration is shorter:
* - "4:56"
* - "14:06"
* - Less than one minute:
* - "0:00"
* - "0:01"
* - "0:59"
*/
fun Long.toHumanReadableDuration(): String {
val inSeconds = this / 1_000
val hours = inSeconds / 3_600
val minutes = (inSeconds % 3_600) / 60
val seconds = inSeconds % 60
return if (hours > 0) {
String.format(Locale.US, "%d:%02d:%02d", hours, minutes, seconds)
} else {
String.format(Locale.US, "%d:%02d", minutes, seconds)
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2024 New Vector Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only
* Please see LICENSE in the repository root for full details.
*/
package io.element.android.libraries.dateformatter.api
import com.google.common.truth.Truth.assertThat
import org.junit.Test
class DurationFormatterTest {
@Test
fun `format seconds only`() {
assertThat(buildDuration().toHumanReadableDuration()).isEqualTo("0:00")
assertThat(buildDuration(seconds = 1).toHumanReadableDuration()).isEqualTo("0:01")
assertThat(buildDuration(seconds = 59).toHumanReadableDuration()).isEqualTo("0:59")
}
@Test
fun `format minutes and seconds`() {
assertThat(buildDuration(minutes = 1).toHumanReadableDuration()).isEqualTo("1:00")
assertThat(buildDuration(minutes = 1, seconds = 30).toHumanReadableDuration()).isEqualTo("1:30")
assertThat(buildDuration(minutes = 59, seconds = 59).toHumanReadableDuration()).isEqualTo("59:59")
}
@Test
fun `format hours, minutes and seconds`() {
assertThat(buildDuration(hours = 1).toHumanReadableDuration()).isEqualTo("1:00:00")
assertThat(buildDuration(hours = 1, minutes = 1, seconds = 1).toHumanReadableDuration()).isEqualTo("1:01:01")
assertThat(buildDuration(hours = 24, minutes = 59, seconds = 59).toHumanReadableDuration()).isEqualTo("24:59:59")
assertThat(buildDuration(hours = 25, minutes = 0, seconds = 0).toHumanReadableDuration()).isEqualTo("25:00:00")
}
private fun buildDuration(
hours: Int = 0,
minutes: Int = 0,
seconds: Int = 0
): Long {
return (hours * 60 * 60 + minutes * 60 + seconds) * 1000L
}
}