Java Cookbook
Format a time amount
Problem:
You want to format a time amount like "5 days" for a locale.
Solution:
TimeUnitFormat from icu4j provides some excellent formatting options for time units. To use you specify a TimeUnitAmount which contains an amount and a unit. Then specify a locale on the TimeUnitFormat.
To format 1 day in French:
//Get a TimeUnit
TimeUnit unit = TimeUnit.DAY;
//Specify the unit amount
TimeUnitAmount amount = new TimeUnitAmount(1,unit);
TimeUnitAmount amount2= new TimeUnitAmount(3,unit);
//Get a unit format
TimeUnitFormat format = new TimeUnitFormat();
//Get and set a ULocale
ULocale uloc = new ULocale("fr");
format.setLocale(uloc);
//Format and output
System.out.println(format.format(amount));
System.out.println(format.format(amount2));
The output:
1 jour
3 jours
If you are testing any of these recipes in Eclipse and the characters are not displaying correctly in your console visit http://i18ncookbook.com/eclipse_settings.
This site is ad supported. I hope you find something among our sponsors worth clicking. ;)
i18n search