Java Reference
In-Depth Information
You want to display numbers, dates, and time in a user-friendly way that conforms to
the language and cultural expectations of your customers.
Solution
The display format for numbers, dates, and time varies across the world and depends
on your user's language and cultural region. Additionally, text collation rules vary by
language. The java.util.Locale class represents a specific language and region
of the world. By determining and using your customer's locale, you can apply that loc-
ale to a variety of format classes, which can be used to create user-visible data in ex-
pected forms. Classes that use Locale instances to modify their behavior for a partic-
ular language or region are called locale-sensitive classes. You can learn more about
locale-sensitive classes in Chapter 4 , “Numbers and Dates.” That chapter shows you
how to use Locale instances in the NumberFormat and DateFormat classes. In
this recipe, however, you learn different options for creating these Locale instances.
You can create a Locale instance in any of the following ways:
Use the Locale.Builder class to configure and build a Locale
object.
Use the static Locale.forLanguageTag() method.
Use the Locale constructors to create an object.
Use preconfigured static Locale objects.
The Java Locale.Builder class has setter methods that allow you to create loc-
ales that can be transformed into well-formed Best Common Practices (BCP) 47 lan-
guage tags. The “How It Works” section describes the BCP 47 standard in more detail.
For now, you should simply understand that a Builder creates Locale instances
that comply with that standard.
The following code snippet from the
org.java8recipes.chapter12.recipe12_2.Recipe12_2 class demon-
strates how to create Builder and Locale instances. You use the created locales in
locale-sensitive classes to produce culturally correct display formats:
private static final long number = 123456789L;
private static final Date now = new Date();
Search WWH ::




Custom Search