Java Reference
In-Depth Information
public static final DateFormat getDateTimeInstance(int dateStyle, int
timeStyle, Locale loc)
gets a date/time formatter with the specified date style, time
style, and locale.
The
DateFormat
class also defi nes a third overloaded version for each of these methods
that takes in the style
int
s but not the
Locale
reference, so the default locale is used for
those methods. After you obtain a
DateFormat
object, you use its
format
and
parse
meth-
ods to format and parse dates and times in the specifi ed locale, which we discuss next.
The
DateFormat.format
Methods
The
DateFormat
class defi nes three
format
methods, but you only need to know one of
these for the exam:
public final String format(Date date)
.
The
date
parameter is of type
java.util.Date
, a useful class that represents a specifi c
instance in time as milliseconds. A
Date
object is instantiated by passing in a
long
that
represents the time in milliseconds from January 1, 1970 at 00:00:00 GMT. (The no-
argument constructor of
Date
returns the current time on the underlying platform.) The
format
method returns the
String
representation of the given
Date
based on the specifi ed
locale of the
DateFormat
object.
Let's look at an example. The following code creates a
Date
object that lies on January
31, 1984, and formats the date in both the
SHORT
and
FULL
styles:
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat full =DateFormat.getDateInstance(DateFormat.FULL);
Date d = new Date(444444444000L);
System.out.println(df.format(d));
System.out.println(full.format(d));
The output of the statements is
1/31/84
Tuesday, January 31, 1984
To include the time in the format of a date, use a
DateFormat
object from the
get
DateTimeInstance
method. The following statement formats the same
Date
object from the
previous code using a
MEDIUM
date style and a
FULL
time style:
DateFormat dtf = DateFormat.getDateTimeInstance(
DateFormat.MEDIUM,
DateFormat.FULL);
System.out.println(dtf.format(d));
The output of the previous statements depends on the time zone and locale, but it will
look something like this:
Jan 31, 1984 5:47:24 PM MST
Search WWH ::
Custom Search