Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show localized date units in a formatted string in Java/Android?

Let's say I have a period of days:

Period p = Period.ofDays(3);

And I want to format the period with the "days" label in the string to get this string as output:

// "3 days"

...but, I want to localize the "days" component, so I can't use a formatted string like the following, otherwise it will only ever appear correctly in English:

String.format("%d days", numberOfDays); // Won't localize 'days'

What APIs are there in Java/Kotlin/Android to represent a period of time, like hours, days, weeks, years in a locale? I would rather not localize those words by myself if I can let the API do it.

like image 807
Benstrom Avatar asked Apr 17 '26 12:04

Benstrom


1 Answers

As suggested in one comment, you can use my lib Time4J and use following code:

Period p = Period.ofDays(3);
Locale loc = Locale.ENGLISH; // or any other supported locale
String formatted = PrettyTime.of(loc).print(p); // 3 days

The tutorial also contains a list of currently supported languages. By the way, the Time4J-equivalent for java.time.Period would be net.time4j.Duration<CalendarUnit> if you are interested in other features like normalization or extended ISO-compatibility etc.

Note: If you are on Android then you should rather use the sister library Time4A instead of Time4J but the presented code would be the same.

like image 126
Meno Hochschild Avatar answered Apr 20 '26 01:04

Meno Hochschild



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!