How to format localized time duration like "1 minute 30 seconds"?
Asked Answered
S

1

6

Is there a way to format a localized time duration in Kotlin or Java? I have a Duration, and I want to display it in a localized, human readable string like "1 minute 30 seconds" or "1m 30s".

I did find RelativeDateTimeFormatter, but it only appears to generate time parts that are in the future or past tense like "1 minute ago" or "in 1 minute". Is there a way to configure it to generate the present tense?

Snowshoe answered 19/12, 2022 at 21:16 Comment(6)
This is not a duplicate, none of the answers in the linked question are localized.Snowshoe
Interesting… The Unicode CLDR (used by modern implementations of Java) does indeed seem to offer localization data for duration values such as minutes. I am voting to re-open.Caphaitien
I suggest you add a link to documentation on this RelativeDateTimeFormatter class you mention. I do not see it bundled with Java SE.Caphaitien
Joda seems to have had classes for formatting Period. It's odd that these didn't end up in java.time. (Of course, that doesn't deal with the localisation, but it's half of the issue).Tamikatamiko
As the other comments seem to indicate, I believe that this is not built into Java (probably not Kotlin either).Melanesian
Did you check How to format a duration in java??Gland
L
1

After debugging of RelativeDateTimeFormatters ICU usage I found this solution:

val measureFormat = android.icu.text.MeasureFormat.getInstance(Locale.getDefault(), MeasureFormat.FormatWidth.WIDE)
val minutes = measureFormat.formatMeasures(Measure(1, MeasureUnit.MINUTE))
val seconds = measureFormat.formatMeasures(Measure(30, MeasureUnit.SECOND))
val result = "$minutes $seconds"

Results in: 1 minute 30 seconds

Note: measureFormat.formatMeasures($SECOND, $MINUTE) results in 1 minute, 30 seconds

Lipolysis answered 14/5, 2024 at 12:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.