Java Reference
In-Depth Information
The Date for France:
In FULL is samedi 9 f vrier 2002
In LONG is 9 f vrier 2002
In MEDIUM is 9 f vr. 2002
In SHORT is 09/02/02
How It Works
The program creates a
Date
object for the current date and time, and an array of
Locale
objects for four
countries using values defined in the
Locale
class. It then creates an array of the four possible styles, and
another array containing a
String
representation for each style that will be used in the output.
The output is produced in the nested
for
loops. The outer loop iterates over the countries, and the
inner loop iterates over the four styles for each country. A
DateFormat
object is created for each
combination of style and country, and the
format()
method for the
DateFormat
object is called to
produce the formatted date string in the inner call to
println()
.
There are a couple of ways you could change the program. You could initialize the
locales
[]
array
with the expression
DateFormat.getAvailableLocales()
. This will return an array of type
Locale
containing all of the supported locales, but be warned - there are a lot of them. You'll also find
that the characters won't display for many countries because your machine doesn't support the country-
specific character set. You could also use the method
getTimeInstance()
or
getDateTimeInstance()
instead of
getDateInstance()
to see what sort of output they generate.
Under the covers, a
DateFormat
object contains a
DateFormatSymbols
object that contains all the
strings for the names of days of the week and other fixed information related to time and dates. This
class is also in the
java.text
package. Normally you don't use the
DateFormatSymbols
class
directly, but it can be useful when all you want are the days of the week.
Obtaining a Date Object from a String
The
parse()
method for a
DateFormat
object interprets a
String
object passed as an argument as a
date and time, and returns a
Date
object corresponding to the date and the time. The
parse()
method
will throw a
ParseException
if the
String
object can't be converted to a
Date
object, so you must
call it within a
try
block.
The
String
argument to the
parse()
method must correspond to the country and style that you used
when you obtained the
DateFormat
object. This makes it a bit tricky to use successfully. For example,
the following code will parse the string properly:
Date aDate;
DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL, Locale.US);
try {
aDate = fmt.parse("Saturday, July 4, 1998 ");
System.out.println("The Date string is: " + fmt.format(aDate));
} catch(ParseException e) {
System.out.println(e);
}
This works because the string is what would be produced by the locale and style. If you omit the day
from the string, or you use the
LONG
style or a different locale, a
ParseException
will be thrown.