Java: Formatting

Locale

Two category of Locale:

  • Locale.DISPLAY (used for Locale meta-information, e.g. language: German / Deutsch)
  • Locale.FORMAT (used for formatting)

Can have a default locale for each: Locale.setDefault(Locale.DISPLAY, Locale.GERMANY);

Locale.getDefault()
Locale.UK, Locale.USA, Locale.GERMANY, Locale.GERMAN
Locale myLocale = new Locale(“en”);  //  = Locale.ENGLISH
Locale myLocale = new Locale(“en”, “GB”); // =  Locale.UK
Locale myLocale = new Locale(“de”, “DE”);  // =  Locale.GERMANY
Locale.setDefault(Locale.GERMANY);

Number Formatting

Can use the NumberFormat Class (not threadsafe)

NumberFormat myNF = NumberFormat.getInstance( optnalLocale );
NumberFormat myNF = NumberFormat.getCurrencyInstance( optnalLocale );
NumberFormat myNF = NumberFormat.getIntegerInstance( optnalLocale );
NumberFormat myNF = NumberFormat.getPercentInstance( optnalLocale );

NumberFormat myNF = new DecimalFormat(“##0.0”);
//           ‘0’ = digit always shown, ‘#’ digit optional

myNF.format(123.654f); // output string in locale format

myNF.parse(“123,654”); // parses using locale format – around 123 (France) or 123000 (UK)

DateTimeFormatter

The DateTimeFormatter works with simplified FormatStyles:

FULL, LONG, MEDIUM, SHORT

or customisable pattern strings (e.g. “yyyy-MM-ddTHH-mm-ssZ”).

DateTimeFormatter myDTF = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);

DateTimeFormatter myDTF = DateTimeFormatter.ofPattern(“yyyy-MM-ddTHH-mm-ssZ”);
DateTimeFormatter myDTF2 = myDTF.withLocale(myLocale);
DateTimeFormatter myDTF3 = myDTF2.withZone(myZoneId);

myDTF3.format(myDateTime);  // outputs string
or
myDateTime.format(myDTF3);  // outputs string

Many prebuilt DateTimeFormatters:

  • DateTimeFormatter.BASIC_ISO_DATE
  • DateTimeFormatter.ISO_INSTANT
  • DateTimeFormatter.ISO_LOCAL_DATE(_TIME)
  • DateTimeFormatter.ISO_ZONED_DATE_TIME

Codes for building format pattern strings (see DateTimeFormatter docs)

  • M – Month Numeric
  • L – Month Text
  • d – day of month
  • D – day of year
  • E – day of week
  • a – AM or PM
  • h – 12 hours
  • H – 24 hours
  • S – fraction of second (milli)
  • n – nano of second
  • V – Time Zone ID
  • z – Time Zone text
  • Z – Time Zone offset

Resource Bundles

ResourceBundles give text look-ups that can change for each locale

ResourceBundle rb = ResourceBundle.getBundle(“baseName”, optionalLocale);

Search order (Default Locale = en_GB, Requested Locale = fr_FR)

  • baseName_fr_FR.properties
  • baseName_fr.properties
  • baseName_en_GB.properties
  • baseName_en.properties
  • baseName.properties
  • raise exception

Formatting Messages

MessageFormat can be used to format & parse texts using parameters

MessageFormat.format(“Testing, testing {0}, {1}”, “one”, “two”);
//           →  Testing, testing one, two

MessageFormat myMF = new MessageFormat(“Testing, testing {0}, {1}”);
Object[] theParms = myMF.parse(“Testing, testing one, two”); // → {one, two}