DateFormat provides several ways to format and parse dates and times. It is a subclass of the general
Format class, discussed in Section 24.6.2 on page 710. There are three kinds of formatters, each returned by
different static methods: date formatters from geTDateInstance, time formatters from
getTimeInstance, and date/time formatters from getdateTimeInstance. Each of these formatters
understands four formatting styles: SHORT, MEDIUM, LONG, and FULL, which are constants defined in
DateFormat. And for each of them you can either use the default locale or specify one. For example, to get
a medium date formatter in the default locale, you would use
Format fmt = DateFormat.getDateInstance(DateFormat.MEDIUM);
To get a date and time formatter that uses dates in short form and times in full form in a Japanese locale, you
would use
Locale japan = new Locale("jp", "JP");
Format fmt = DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.FULL, japan
);
For all the various "get instance" methods, if both formatting style and locale are specified the locale is the
last parameter. The date/time methods require two formatting styles: the first for the date part, the second for
the time. The simplest getInstance method takes no arguments and returns a date/time formatter for short
formats in the default locale. The getAvailableLocales method returns an array of Locale objects for
which date and time formatting is configured.
The following list shows how each formatting style is expressed for the same date. The output is from a
date/time formatter for U.S. locales, with the same formatting mode used for both dates and times:
FULL: Friday, August 29, 1986 5:00:00 PM EDT
LONG: August 29, 1986 5:00:00 PM EDT
MEDIUM: Aug 29, 1986 5:00:00 PM
SHORT: 8/29/86 5:00 PM
Each DateFormat object has an associated calendar and time zone set by the "get instance" method that
created it. They are returned by getCalendar and getTimeZone, respectively. You can set these values
by using setCalendar and setTimeZone. Each DateFormat object has a reference to a
NumberFormat object for formatting numbers. You can use the methods getNumberFormat and
setNumberFormat. (Number formatting is covered briefly in Section 24.6.2 on page 710.)
You format dates with one of several format methods based on the formatting parameters described earlier:
public final Stringformat(Date date)
Returns a formatted string for date.
public abstract StringBufferformat(Date date, StringBuffer
appendTo, FieldPosition pos)
Adds the formatted string for date to the end of appendTo.