Java Reference
In-Depth Information
You format dates with one of several
format
methods based on the
formatting parameters described earlier:
public final String
format(Date date)
Returns a formatted string for
date
.
public abstract StringBuffer
format(Date date, StringBuffer ap-
pendTo, FieldPosition pos)
Adds the formatted string for
date
to the end of
appendTo
.
public abstract StringBuffer
format(Object obj, StringBuffer ap-
pendTo, FieldPosition pos)
Adds the formatted string for
obj
to the end of
appendTo
. The
object can be either a
Date
or a
Number
whose
longValue
is a
time in milliseconds.
The
pos
argument is a
FieldPosition
object that tracks the starting and
ending index for a specific field within the formatted output. You cre-
ate a
FieldPosition
object by passing an integer code that represents
the field that the object should track. These codes are static fields in
DateFormat
, such as
MINUTE_FIELD
or
MONTH_FIELD
. Suppose you construct
a
FieldPosition
object
pos
with
MINUTE_FIELD
and then pass it as an ar-
gument to a
format
method. When
format
returns, the
getBeginIndex
and
getEndIndex
methods of
pos
will return the start and end indices of the
characters representing minutes within the formatted string. A specific
formatter could also use the
FieldPosition
object to align the represen-
ted field within the formatted string. To make that happen, you would
first invoke the
setBeginIndex
and
setEndIndex
methods of
pos
, passing
the indices where you would like that field to start and end in the
formatted string. Exactly how the formatter aligns the formatted text
depends on the formatter implementation.
A
DateFormat
object can also be used to parse dates. Date parsing can
be lenient or not, depending on your preference. Lenient date parsing