How can I format the length of time for a string with localized time units on Android?

I would like to format the duration of the time (e.g. seconds) into a String that will contain the localized names of the time units. For example, to enter 8692, I would get the string "2h 24min 52sec" when the time units are correctly localized for each language. Is there any class in Android that can do this? Does anyone know of some external openource library for this? Thank.

+3


source to share


1 answer


I don't know of any open source libraries, but if I understand the problem correctly, it shouldn't be too hard to do it manually:

public static String foo(int duration) {
    int hours = duration/3600;
    int minutes = (duration%3600)/60;
    int seconds = duration%60;
    return hours + getResources().getString(R.string.hours) +
           minutes + getResources().getString(R.string.minutes) +
           seconds + getResources().getString(R.string.seconds);
}

      

Then you define those strings in strings.xml

and localize them as usual. (See http://developer.android.com/guide/topics/resources/localization.html )

As of Android, there is a class Duration

( http://developer.android.com/reference/javax/xml/datatype/Duration.html ) that you can use, but its method is toString()

not exactly what you want.



Edit just for completeness: now I understand your problem better, you don't want to localize all time units manually. The Unicode Common Locale Data Repository has some (well, a lot) interesting data. They provide XML data for pretty much anything you might want to localize, for example. de.xml

(German):

<unit type="duration-hour">
    <displayName>Stunden</displayName>
    <unitPattern count="one">{0} Stunde</unitPattern>
    <unitPattern count="other">{0} Stunden</unitPattern>
    <perUnitPattern>{0} pro Stunde</perUnitPattern>
</unit>

      

I assume this is overkill, but as I said, for completeness.

+2


source







All Articles