FileDocCategorySizeDatePackage
DateFormat.javaAPI DocAndroid 1.5 API38506Wed May 06 22:41:06 BST 2009java.text

DateFormat

public abstract class DateFormat extends Format
An abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The date/time formatting subclass, such as {@link SimpleDateFormat}, allows for formatting (i.e., date -> text), parsing (text -> date), and normalization. The date is represented as a {@code Date} object or as the milliseconds since January 1, 1970, 00:00:00 GMT.

DateFormat provides many class methods for obtaining default date/time formatters based on the default or a given locale and a number of formatting styles. The formatting styles include FULL, LONG, MEDIUM, and SHORT. More details and examples for using these styles are provided in the method descriptions.

{@code DateFormat} helps you to format and parse dates for any locale. Your code can be completely independent of the locale conventions for months, days of the week, or even the calendar format: lunar vs. solar.

To format a date for the current Locale, use one of the static factory methods:

myString = DateFormat.getDateInstance().format(myDate);

If you are formatting multiple dates, it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.

DateFormat df = DateFormat.getDateInstance();
for (int i = 0; i < a.length; ++i) {
output.println(df.format(myDate[i]) + "; ");
}

To format a number for a different locale, specify it in the call to {@code getDateInstance}:

DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);

{@code DateFormat} can also be used to parse strings:

myDate = df.parse(myString);

Use {@code getDateInstance} to get the normal date format for a country. Other static factory methods are available: Use {@code getTimeInstance} to get the time format for a country. Use {@code getDateTimeInstance} to get the date and time format. You can pass in different options to these factory methods to control the length of the result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the locale, but generally:

  • SHORT is completely numeric, such as 12.13.52 or 3:30pm
  • MEDIUM is longer, such as Jan 12, 1952
  • LONG is longer, such as January 12, 1952 or 3:30:32pm
  • FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.

If needed, the time zone can be set on the format. For even greater control over the formatting or parsing, try casting the {@code DateFormat} you get from the factory methods to a {@code SimpleDateFormat}. This will work for the majority of countries; just remember to put it in a try block in case you encounter an unusual one.

There are versions of the parse and format methods which use {@code ParsePosition} and {@code FieldPosition} to allow you to

  • progressively parse through pieces of a string;
  • align any particular field.

Synchronization

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

see
NumberFormat
see
SimpleDateFormat
see
Calendar
see
TimeZone
since
Android 1.0

Fields Summary
private static final long
serialVersionUID
protected Calendar
calendar
The calendar that this {@code DateFormat} uses to format a number representing a date.
protected NumberFormat
numberFormat
The number format used to format a number.
public static final int
DEFAULT
The format style constant defining the default format style. The default is MEDIUM.
public static final int
FULL
The format style constant defining the full style.
public static final int
LONG
The format style constant defining the long style.
public static final int
MEDIUM
The format style constant defining the medium style.
public static final int
SHORT
The format style constant defining the short style.
public static final int
ERA_FIELD
The {@code FieldPosition} selector for 'G' field alignment, corresponds to the {@link Calendar#ERA} field.
public static final int
YEAR_FIELD
The {@code FieldPosition} selector for 'y' field alignment, corresponds to the {@link Calendar#YEAR} field.
public static final int
MONTH_FIELD
The {@code FieldPosition} selector for 'M' field alignment, corresponds to the {@link Calendar#MONTH} field.
public static final int
DATE_FIELD
The {@code FieldPosition} selector for 'd' field alignment, corresponds to the {@link Calendar#DATE} field.
public static final int
HOUR_OF_DAY1_FIELD
The {@code FieldPosition} selector for 'k' field alignment, corresponds to the {@link Calendar#HOUR_OF_DAY} field. {@code HOUR_OF_DAY1_FIELD} is used for the one-based 24-hour clock. For example, 23:59 + 01:00 results in 24:59.
public static final int
HOUR_OF_DAY0_FIELD
The {@code FieldPosition} selector for 'H' field alignment, corresponds to the {@link Calendar#HOUR_OF_DAY} field. {@code HOUR_OF_DAY0_FIELD} is used for the zero-based 24-hour clock. For example, 23:59 + 01:00 results in 00:59.
public static final int
MINUTE_FIELD
FieldPosition selector for 'm' field alignment, corresponds to the {@link Calendar#MINUTE} field.
public static final int
SECOND_FIELD
FieldPosition selector for 's' field alignment, corresponds to the {@link Calendar#SECOND} field.
public static final int
MILLISECOND_FIELD
FieldPosition selector for 'S' field alignment, corresponds to the {@link Calendar#MILLISECOND} field.
public static final int
DAY_OF_WEEK_FIELD
FieldPosition selector for 'E' field alignment, corresponds to the {@link Calendar#DAY_OF_WEEK} field.
public static final int
DAY_OF_YEAR_FIELD
FieldPosition selector for 'D' field alignment, corresponds to the {@link Calendar#DAY_OF_YEAR} field.
public static final int
DAY_OF_WEEK_IN_MONTH_FIELD
FieldPosition selector for 'F' field alignment, corresponds to the {@link Calendar#DAY_OF_WEEK_IN_MONTH} field.
public static final int
WEEK_OF_YEAR_FIELD
FieldPosition selector for 'w' field alignment, corresponds to the {@link Calendar#WEEK_OF_YEAR} field.
public static final int
WEEK_OF_MONTH_FIELD
FieldPosition selector for 'W' field alignment, corresponds to the {@link Calendar#WEEK_OF_MONTH} field.
public static final int
AM_PM_FIELD
FieldPosition selector for 'a' field alignment, corresponds to the {@link Calendar#AM_PM} field.
public static final int
HOUR1_FIELD
FieldPosition selector for 'h' field alignment, corresponding to the {@link Calendar#HOUR} field. {@code HOUR1_FIELD} is used for the one-based 12-hour clock. For example, 11:30 PM + 1 hour results in 12:30 AM.
public static final int
HOUR0_FIELD
The {@code FieldPosition} selector for 'z' field alignment, corresponds to the {@link Calendar#ZONE_OFFSET} and {@link Calendar#DST_OFFSET} fields.
public static final int
TIMEZONE_FIELD
The {@code FieldPosition} selector for 'z' field alignment, corresponds to the {@link Calendar#ZONE_OFFSET} and {@link Calendar#DST_OFFSET} fields.
Constructors Summary
protected DateFormat()
Constructs a new instance of {@code DateFormat}.

since
Android 1.0


                    
      
    
Methods Summary
private static voidcheckDateStyle(int style)

        if (!(style == SHORT || style == MEDIUM || style == LONG
                || style == FULL || style == DEFAULT)) {
            // text.0E=Illegal date style: {0}
            throw new IllegalArgumentException(Messages.getString(
                    "text.0E", style)); //$NON-NLS-1$
        }
    
private static voidcheckTimeStyle(int style)

        if (!(style == SHORT || style == MEDIUM || style == LONG
                || style == FULL || style == DEFAULT)) {
            // text.0F=Illegal time style: {0}
            throw new IllegalArgumentException(Messages.getString(
                    "text.0F", style)); //$NON-NLS-1$
        }
    
public java.lang.Objectclone()
Returns a new instance of {@code DateFormat} with the same properties.

return
a shallow copy of this {@code DateFormat}.
see
java.lang.Cloneable
since
Android 1.0

        DateFormat clone = (DateFormat) super.clone();
        clone.calendar = (Calendar) calendar.clone();
        clone.numberFormat = (NumberFormat) numberFormat.clone();
        return clone;
    
public booleanequals(java.lang.Object object)
Compares this date format with the specified object and indicates if they are equal.

param
object the object to compare with this date format.
return
{@code true} if {@code object} is a {@code DateFormat} object and it has the same properties as this date format; {@code false} otherwise.
see
#hashCode
since
Android 1.0

        if (this == object) {
            return true;
        }
        if (!(object instanceof DateFormat)) {
            return false;
        }
        DateFormat dateFormat = (DateFormat) object;
        return numberFormat.equals(dateFormat.numberFormat)
                && calendar.getTimeZone().equals(
                        dateFormat.calendar.getTimeZone())
                && calendar.getFirstDayOfWeek() == dateFormat.calendar
                        .getFirstDayOfWeek()
                && calendar.getMinimalDaysInFirstWeek() == dateFormat.calendar
                        .getMinimalDaysInFirstWeek()
                && calendar.isLenient() == dateFormat.calendar.isLenient();
    
public final java.lang.StringBufferformat(java.lang.Object object, java.lang.StringBuffer buffer, java.text.FieldPosition field)
Formats the specified object as a string using the pattern of this date format and appends the string to the specified string buffer.

If the {@code field} member of {@code field} contains a value specifying a format field, then its {@code beginIndex} and {@code endIndex} members will be updated with the position of the first occurrence of this field in the formatted text.

param
object the source object to format, must be a {@code Date} or a {@code Number}. If {@code object} is a number then a date is constructed using the {@code longValue()} of the number.
param
buffer the target string buffer to append the formatted date/time to.
param
field on input: an optional alignment field; on output: the offsets of the alignment field in the formatted text.
return
the string buffer.
exception
IllegalArgumentException if {@code object} is neither a {@code Date} nor a {@code Number} instance.
since
Android 1.0

        if (object instanceof Date) {
            return format((Date) object, buffer, field);
        }
        if (object instanceof Number) {
            return format(new Date(((Number) object).longValue()), buffer,
                    field);
        }
        throw new IllegalArgumentException();
    
public final java.lang.Stringformat(java.util.Date date)
Formats the specified date using the rules of this date format.

param
date the date to format.
return
the formatted string.
since
Android 1.0

        return format(date, new StringBuffer(), new FieldPosition(0))
                .toString();
    
public abstract java.lang.StringBufferformat(java.util.Date date, java.lang.StringBuffer buffer, java.text.FieldPosition field)
Formats the specified date as a string using the pattern of this date format and appends the string to the specified string buffer.

If the {@code field} member of {@code field} contains a value specifying a format field, then its {@code beginIndex} and {@code endIndex} members will be updated with the position of the first occurrence of this field in the formatted text.

param
date the date to format.
param
buffer the target string buffer to append the formatted date/time to.
param
field on input: an optional alignment field; on output: the offsets of the alignment field in the formatted text.
return
the string buffer.
since
Android 1.0

public static java.util.Locale[]getAvailableLocales()
Gets the list of installed locales which support {@code DateFormat}.

return
an array of locales.
since
Android 1.0

        return Locale.getAvailableLocales();
    
public java.util.CalendargetCalendar()
Returns the calendar used by this {@code DateFormat}.

return
the calendar used by this date format.
since
Android 1.0

        return calendar;
    
public static final java.text.DateFormatgetDateInstance(int style)
Returns a {@code DateFormat} instance for formatting and parsing dates in the specified style for the default locale.

param
style one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
return
the {@code DateFormat} instance for {@code style} and the default locale.
throws
IllegalArgumentException if {@code style} is not one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
since
Android 1.0

        checkDateStyle(style);
        return getDateInstance(style, Locale.getDefault());
    
public static final java.text.DateFormatgetDateInstance(int style, java.util.Locale locale)
Returns a {@code DateFormat} instance for formatting and parsing dates in the specified style for the specified locale.

param
style one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
param
locale the locale.
throws
IllegalArgumentException if {@code style} is not one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
return
the {@code DateFormat} instance for {@code style} and {@code locale}.
since
Android 1.0

        checkDateStyle(style);
        ResourceBundle bundle = getBundle(locale);
        String pattern = bundle.getString("Date_" + getStyleName(style)); //$NON-NLS-1$
        return new SimpleDateFormat(pattern, locale);
    
public static final java.text.DateFormatgetDateInstance()
Returns a {@code DateFormat} instance for formatting and parsing dates in the DEFAULT style for the default locale.

return
the {@code DateFormat} instance for the default style and locale.
since
Android 1.0

        return getDateInstance(DEFAULT);
    
public static final java.text.DateFormatgetDateTimeInstance()
Returns a {@code DateFormat} instance for formatting and parsing dates and time values in the DEFAULT style for the default locale.

return
the {@code DateFormat} instance for the default style and locale.
since
Android 1.0

        return getDateTimeInstance(DEFAULT, DEFAULT);
    
public static final java.text.DateFormatgetDateTimeInstance(int dateStyle, int timeStyle)
Returns a {@code DateFormat} instance for formatting and parsing of both dates and time values in the manner appropriate for the default locale.

param
dateStyle one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
param
timeStyle one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
return
the {@code DateFormat} instance for {@code dateStyle}, {@code timeStyle} and the default locale.
throws
IllegalArgumentException if {@code dateStyle} or {@code timeStyle} is not one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
since
Android 1.0

        checkTimeStyle(timeStyle);
        checkDateStyle(dateStyle);
        return getDateTimeInstance(dateStyle, timeStyle, Locale.getDefault());
    
public static final java.text.DateFormatgetDateTimeInstance(int dateStyle, int timeStyle, java.util.Locale locale)
Returns a {@code DateFormat} instance for formatting and parsing dates and time values in the specified styles for the specified locale.

param
dateStyle one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
param
timeStyle one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
param
locale the locale.
return
the {@code DateFormat} instance for {@code dateStyle}, {@code timeStyle} and {@code locale}.
throws
IllegalArgumentException if {@code dateStyle} or {@code timeStyle} is not one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
since
Android 1.0

        checkTimeStyle(timeStyle);
        checkDateStyle(dateStyle);
        ResourceBundle bundle = getBundle(locale);
        String pattern = bundle.getString("Date_" + getStyleName(dateStyle)) //$NON-NLS-1$
                + " " + bundle.getString("Time_" + getStyleName(timeStyle)); //$NON-NLS-1$ //$NON-NLS-2$
        return new SimpleDateFormat(pattern, locale);
    
public static final java.text.DateFormatgetInstance()
Returns a {@code DateFormat} instance for formatting and parsing dates and times in the SHORT style for the default locale.

return
the {@code DateFormat} instance for the SHORT style and default locale.
since
Android 1.0

        return getDateTimeInstance(SHORT, SHORT);
    
public java.text.NumberFormatgetNumberFormat()
Returns the {@code NumberFormat} used by this {@code DateFormat}.

return
the {@code NumberFormat} used by this date format.
since
Android 1.0

        return numberFormat;
    
static java.lang.StringgetStyleName(int style)

        String styleName;
        switch (style) {
            case SHORT:
                styleName = "SHORT"; //$NON-NLS-1$
                break;
            case MEDIUM:
                styleName = "MEDIUM"; //$NON-NLS-1$
                break;
            case LONG:
                styleName = "LONG"; //$NON-NLS-1$
                break;
            case FULL:
                styleName = "FULL"; //$NON-NLS-1$
                break;
            default:
                styleName = ""; //$NON-NLS-1$
        }
        return styleName;
    
public static final java.text.DateFormatgetTimeInstance()
Returns a {@code DateFormat} instance for formatting and parsing time values in the DEFAULT style for the default locale.

return
the {@code DateFormat} instance for the default style and locale.
since
Android 1.0

        return getTimeInstance(DEFAULT);
    
public static final java.text.DateFormatgetTimeInstance(int style)
Returns a {@code DateFormat} instance for formatting and parsing time values in the specified style for the default locale.

param
style one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
return
the {@code DateFormat} instance for {@code style} and the default locale.
throws
IllegalArgumentException if {@code style} is not one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
since
Android 1.0

        checkTimeStyle(style);
        return getTimeInstance(style, Locale.getDefault());
    
public static final java.text.DateFormatgetTimeInstance(int style, java.util.Locale locale)
Returns a {@code DateFormat} instance for formatting and parsing time values in the specified style for the specified locale.

param
style one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
param
locale the locale.
throws
IllegalArgumentException if {@code style} is not one of SHORT, MEDIUM, LONG, FULL, or DEFAULT.
return
the {@code DateFormat} instance for {@code style} and {@code locale}.
since
Android 1.0

        checkTimeStyle(style);
        ResourceBundle bundle = getBundle(locale);
        String pattern = bundle.getString("Time_" + getStyleName(style)); //$NON-NLS-1$
        return new SimpleDateFormat(pattern, locale);
    
public java.util.TimeZonegetTimeZone()
Returns the time zone of this date format's calendar.

return
the time zone of the calendar used by this date format.
since
Android 1.0

        return calendar.getTimeZone();
    
public inthashCode()

        return calendar.getFirstDayOfWeek()
                + calendar.getMinimalDaysInFirstWeek()
                + calendar.getTimeZone().hashCode()
                + (calendar.isLenient() ? 1231 : 1237)
                + numberFormat.hashCode();
    
public booleanisLenient()
Indicates whether the calendar used by this date format is lenient.

return
{@code true} if the calendar is lenient; {@code false} otherwise.
since
Android 1.0

        return calendar.isLenient();
    
public java.util.Dateparse(java.lang.String string)
Parses a date from the specified string using the rules of this date format.

param
string the string to parse.
return
the {@code Date} resulting from the parsing.
exception
ParseException if an error occurs during parsing.
since
Android 1.0

        ParsePosition position = new ParsePosition(0);
        Date date = parse(string, position);
        if (position.getErrorIndex() != -1 || position.getIndex() == 0) {
            // text.19=Unparseable date: {0}
            throw new ParseException(
                    Messages.getString("text.19", string), position.getErrorIndex()); //$NON-NLS-1$
        }
        return date;
    
public abstract java.util.Dateparse(java.lang.String string, java.text.ParsePosition position)
Parses a date from the specified string starting at the index specified by {@code position}. If the string is successfully parsed then the index of the {@code ParsePosition} is updated to the index following the parsed text. On error, the index is unchanged and the error index of {@code ParsePosition} is set to the index where the error occurred.

By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling {@code setLenient(false)}.

param
string the string to parse.
param
position input/output parameter, specifies the start index in {@code string} from where to start parsing. If parsing is successful, it is updated with the index following the parsed text; on error, the index is unchanged and the error index is set to the index where the error occurred.
return
the date resulting from the parse, or {@code null} if there is an error.
since
Android 1.0

public java.lang.ObjectparseObject(java.lang.String string, java.text.ParsePosition position)
Parses a date from the specified string starting at the index specified by {@code position}. If the string is successfully parsed then the index of the {@code ParsePosition} is updated to the index following the parsed text. On error, the index is unchanged and the error index of {@code ParsePosition} is set to the index where the error occurred.

By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling {@code setLenient(false)}.

param
string the string to parse.
param
position input/output parameter, specifies the start index in {@code string} from where to start parsing. If parsing is successful, it is updated with the index following the parsed text; on error, the index is unchanged and the error index is set to the index where the error occurred.
return
the date resulting from the parsing, or {@code null} if there is an error.
since
Android 1.0

        return parse(string, position);
    
public voidsetCalendar(java.util.Calendar cal)
Sets the calendar used by this date format.

param
cal the new calendar.
since
Android 1.0

        calendar = cal;
    
public voidsetLenient(boolean value)
Specifies whether or not date/time parsing shall be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

param
value {@code true} to set the calendar to be lenient, {@code false} otherwise.
since
Android 1.0

        calendar.setLenient(value);
    
public voidsetNumberFormat(java.text.NumberFormat format)
Sets the {@code NumberFormat} used by this date format.

param
format the new number format.
since
Android 1.0

        numberFormat = format;
    
public voidsetTimeZone(java.util.TimeZone timezone)
Sets the time zone of the calendar used by this date format.

param
timezone the new time zone.
since
Android 1.0

        calendar.setTimeZone(timezone);