Java Reference
In-Depth Information
Solution
Use
Locale.getInstance(Locale)
.
Discussion
Classes that provide formatting services, such as
DateFormat
and
NumberFormat
, provide an
overloaded
getInstance()
method that can be called either with no arguments or with a
Locale
argument.
To use these, you can employ one of the predefined locale variables provided by the
Locale
class, or you can construct your own
Locale
object giving a language code and a country
code:
Locale locale1 = Locale.FRANCE; // predefined
Locale locale2 = new Locale("en", "UK"); // English, UK version
Either of these can be used to format a date or a number, as shown in class
UseLocales
:
public
public class
class
UseLocales
UseLocales
{
public
public static
static
void
void
main
(
String
[]
args
) {
Locale frLocale
=
Locale
.
FRANCE
;
// predefined
Locale ukLocale
=
new
new
Locale
(
"en"
,
"UK"
);
// English, UK version
DateFormat defaultDateFormatter
=
DateFormat
.
getDateInstance
(
DateFormat
.
MEDIUM
);
DateFormat frDateFormatter
=
DateFormat
.
getDateInstance
(
DateFormat
.
MEDIUM
,
frLocale
);
DateFormat ukDateFormatter
=
DateFormat
.
getDateInstance
(
DateFormat
.
MEDIUM
,
ukLocale
);
Date now
=
new
new
Date
();
System
.
out
.
println
(
"Default: "
+
' '
+
defaultDateFormatter
.
format
(
now
));
System
.
out
.
println
(
frLocale
.
getDisplayName
() +
' '
+
frDateFormatter
.
format
(
now
));
System
.
out
.
println
(
ukLocale
.
getDisplayName
() +
' '
+
ukDateFormatter
.
format
(
now
));
}
}