Java Reference
In-Depth Information
The Date for Germany:
In FULL is Montag, 27. Juni 2011
In LONG is 27. Juni 2011
In MEDIUM is 27.06.2011
In SHORT is 27.06.11
The Date for France:
In FULL is lundi 27 juin 2011
In LONG is 27 juin 2011
In MEDIUM is 27 juin 2011
In SHORT is 27/06/11
How It Works
By statically importing the constants from the Locale and DateFormat classes, you obviate the need to
qualify the constants in the program and thus make the code a little less cluttered. The nested Styles
enum defines the four possible styles. 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.
The output is produced in the nested for loops. The outer loop iterates over the countries, and the inner
loop is a collection-based for loop that iterates over the styles for each country in the Styles enum. The
ordinal() method for an enum value returns the ordinal for the value in the enumeration. You use this
to specify the style as the first argument to the getDateInstance() method. A DateFormat object is
created for each style and country combination. Calling the format() method for the DateFormat object
produces the date string in the inner call to println() .
You could change the program in a couple ways. You could initialize the locales[] array with
DateFormat.getAvailableLocales() . This returns an array of type Locale containing all of the sup-
ported locales, but be warned — there are a lot of them. You may find that the characters won't display
for some 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 argument as a date and time, and
returns a Date object corresponding to the date and the time. The parse() method throws a ParseExcep-
tion 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. For example, the following code parses 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));
Search WWH ::




Custom Search