APIdia Launch Partner
Top Description Fields Constructors Methods
java.text

public Class SimpleDateFormat

extends DateFormat
Class Inheritance
Imports
java.io.IOException, .InvalidObjectException, .ObjectInputStream, java.time.ZoneOffset, java.util.Calendar, .Date, .GregorianCalendar, .Locale, .Map, .SimpleTimeZone, .SortedMap, .TimeZone, java.util.concurrent.ConcurrentHashMap, .ConcurrentMap, sun.util.calendar.CalendarUtils, .ZoneInfoFile, sun.util.locale.provider.LocaleProviderAdapter, .TimeZoneNameUtility

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date → text), parsing (text → date), and normalization.

SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. However, you are encouraged to create a date-time formatter with either getTimeInstance, getDateInstance, or getDateTimeInstance in DateFormat. Each of these class methods can return a date/time formatter initialized with a default format pattern. You may modify the format pattern using the applyPattern methods as desired. For more information on using these methods, see DateFormat.

Date and Time Patterns

Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.

The following pattern letters are defined (all other characters from 'A' to 'Z' and from 'a' to 'z' not in the table below are reserved). applyPattern(String), applyLocalizedPattern(String), and the SimpleDateFormat constructors throw IllegalArgumentException when passed a pattern containing an unquoted reserved character.

Chart shows pattern letters, date/time component, presentation, and examples.
Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year (context sensitive) Month July; Jul; 07
L Month in year (standalone form) Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
Pattern letters are usually repeated, as their number determines the exact presentation: SimpleDateFormat also supports localized date and time pattern strings. In these strings, the pattern letters described above may be replaced with other, locale dependent, pattern letters. SimpleDateFormat does not deal with the localization of text other than the pattern letters; that's up to the client of the class.

Examples

The following examples show how date and time patterns are interpreted in the U.S. locale. The given date and time are 2001-07-04 12:08:56 local time in the U.S. Pacific Time time zone.
Examples of date and time patterns interpreted in the U.S. locale
Date and Time Pattern Result
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3

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.

API Note

Consider using java.time.format.DateTimeFormatter as an immutable and thread-safe alternative.

Author
Mark Davis, Chen-Lieh Huang, Alan Liu
Since
1.1
See Also
Java Tutorial, java.util.Calendar, java.util.TimeZone, DateFormat, DateFormatSymbols, java.time.format.DateTimeFormatter

Field Summary

Modifier and TypeField and Description
private static final ConcurrentMap<Locale, NumberFormat>
cachedNumberFormatData

Cache NumberFormat instances with Locale key.

private transient char[]
compiledPattern

The compiled pattern.

pack-priv static final int
private Date
defaultCenturyStart

We map dates with two-digit years into the century starting at defaultCenturyStart, which may be any date.

private transient int
private transient boolean
forceStandaloneForm

True if standalone form needs to be used.

private DateFormatSymbols
formatData

The symbols used by this formatter for week names, month names, etc. May not be null.

private static final String
private transient boolean
hasFollowingMinusSign

True when a negative sign follows a number.

private Locale
locale

The Locale used to instantiate this SimpleDateFormat.

private static final int
private transient char
minusSign

The minus sign to be used with format and parse.

private transient NumberFormat
originalNumberFormat

Saved numberFormat and pattern.

private transient String
private String
pattern

The pattern string of this formatter.

private static final int[]
private static final int[]
private static final DateFormat.Field[]
private static final int[]
private int
serialVersionOnStream

The version of the serialized data on the stream.

pack-priv static final long
private static final int
TAG_QUOTE_ASCII_CHAR

Tags for the compiled pattern.

private static final int
pack-priv transient boolean
useDateFormatSymbols

Indicates whether this SimpleDateFormat should use the DateFormatSymbols.

private transient char
zeroDigit

Locale dependent digit zero.

Inherited from java.text.DateFormat:
AM_PM_FIELDcalendarDATE_FIELDDAY_OF_WEEK_FIELDDAY_OF_WEEK_IN_MONTH_FIELDDAY_OF_YEAR_FIELDDEFAULTERA_FIELDFULLHOUR0_FIELDHOUR1_FIELDHOUR_OF_DAY0_FIELDHOUR_OF_DAY1_FIELDLONGMEDIUMMILLISECOND_FIELDMINUTE_FIELDMONTH_FIELDnumberFormatSECOND_FIELDSHORTTIMEZONE_FIELDWEEK_OF_MONTH_FIELDWEEK_OF_YEAR_FIELDYEAR_FIELD

Constructor Summary

AccessConstructor and Description
public
SimpleDateFormat()

Constructs a SimpleDateFormat using the default pattern and date format symbols for the default FORMAT locale

Note

This constructor may not support all locales.

public
SimpleDateFormat(String
the pattern describing the date and time format
pattern
)

Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the default FORMAT locale

Note

This constructor may not support all locales.

public
SimpleDateFormat(String
the pattern describing the date and time format
pattern
,
Locale
the locale whose date format symbols should be used
locale
)

Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the given locale

Note

This constructor may not support all locales.

public
SimpleDateFormat(String
the pattern describing the date and time format
pattern
,
DateFormatSymbols
the date format symbols to be used for formatting
formatSymbols
)

Constructs a SimpleDateFormat using the given pattern and date format symbols.

Method Summary

Modifier and TypeMethod and Description
public void
applyLocalizedPattern(String
a String to be mapped to the new date and time format pattern for this format
pattern
)

Applies the given localized pattern string to this date format.

public void
applyPattern(String
the new date and time pattern for this date format
pattern
)

Applies the given pattern string to this date format.

private void
private boolean
charEquals(char ch1, char ch2)

private void
checkNegativeNumberExpression()

Analyze the negative subpattern of DecimalFormat and set/update values as necessary.

public Object

Returns:

a clone of this SimpleDateFormat
clone
()

Overrides java.text.DateFormat.clone.

Creates a copy of this SimpleDateFormat.

private char[]
compile(String pattern)

Returns the compiled form of the given pattern.

private static void
encode(int tag, int length, StringBuilder buffer)

Encodes the given tag and length and puts encoded char(s) into buffer.

public boolean

Returns:

true if the specified object is equal to this SimpleDateFormat
equals
(Object
object to be compared for equality
obj
)

Overrides java.text.DateFormat.equals.

Compares the specified object with this SimpleDateFormat for equality.

public StringBuffer

Returns:

the formatted date-time string.
format
(Date
the date-time value to be formatted into a date-time string.
date
,
StringBuffer
where the new date-time text is to be appended.
toAppendTo
,
FieldPosition
keeps track on the position of the field within the returned string. For example, given a date-time text "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition is DateFormat#YEAR_FIELD, the begin index and end index of fieldPosition will be set to 0 and 4, respectively. Notice that if the same date-time field appears more than once in a pattern, the fieldPosition will be set for the first occurrence of that date-time field. For instance, formatting a Date to the date-time string "1 PM PDT (Pacific Daylight Time)" using the pattern "h a z (zzzz)" and the alignment field DateFormat#TIMEZONE_FIELD, the begin index and end index of fieldPosition will be set to 5 and 8, respectively, for the first occurrence of the timezone pattern character 'z'.
pos
)

Implements abstract java.text.DateFormat.format.

Formats the given Date into a date/time string and appends the result to the given StringBuffer.

pack-priv final Format.StringBuf
private Format.StringBuf
format(Date date, Format.StringBuf toAppendTo, Format.FieldDelegate delegate)

public AttributedCharacterIterator

Returns:

AttributedCharacterIterator describing the formatted value.
formatToCharacterIterator
(Object
The object to format
obj
)

Overrides java.text.Format.formatToCharacterIterator.

Formats an Object producing an AttributedCharacterIterator.

public Date

Returns:

the start of the 100-year period into which two digit years are parsed
get2DigitYearStart
()

Returns the beginning date of the 100-year period 2-digit years are interpreted as being within.

public DateFormatSymbols

Returns:

the date and time format symbols of this date format
getDateFormatSymbols
()

Gets a copy of the date and time format symbols of this date format.

private Map<String, Integer>
getDisplayContextNamesMap(int field, Locale locale)

Obtains display names map, taking the context into account.

private Map<String, Integer>
getDisplayNamesMap(int field, Locale locale)

public int

Returns:

the hash code value for this SimpleDateFormat
hashCode
()

Overrides java.text.DateFormat.hashCode.

Returns the hash code value for this SimpleDateFormat.

private void
private void
private void
private boolean
isDigit(char c)

private boolean
matchDSTString(String text, int start, int zoneIndex, int standardIndex, String[][] zoneStrings)

private int

Returns:

the new start position if matching succeeded; a negative number indicating matching failure, otherwise.
matchString
(String
the time text being parsed.
text
,
int
where to start parsing.
start
,
int
the date field being parsed.
field
,
String[]
the string array to parsed.
data
,
CalendarBuilder calb)

Private code-size reduction function used by subParse.

private int
matchString(String text, int start, int field, Map<String, Integer> data, CalendarBuilder calb)

Performs the same thing as matchString(String, int, int, String[]).

private int
matchZoneString(String text, int start, String[] zoneNames)

public Date

Returns:

A Date parsed from the string. In case of error, returns null.
parse
(String
A String, part of which should be parsed.
text
,
ParsePosition
A ParsePosition object with index and error index information as described above.
pos
)

Implements abstract java.text.DateFormat.parse.

Parses text from a string to produce a Date.

private void
private void
readObject(ObjectInputStream stream)

After reading an object from the input stream, the format pattern in the object is verified.

public void
set2DigitYearStart(Date
During parsing, two digit years will be placed in the range startDate to startDate + 100 years.
startDate
)

Sets the 100-year period 2-digit years will be interpreted as being in to begin on the date the user specifies.

public void
setDateFormatSymbols(DateFormatSymbols
the new date and time format symbols
newFormatSymbols
)

Sets the date and time format symbols of this date format.

private boolean
shouldObeyCount(int tag, int count)

private void
subFormat(int patternCharIndex, int count, Format.FieldDelegate delegate, Format.StringBuf buffer, boolean useDateFormatSymbols)

Private member function that does the real date/time formatting.

private int

Returns:

the new start position if matching succeeded; -1 indicating matching failure, otherwise. In case matching failure occurred, an error index is set to origPos.errorIndex.
subParse
(String
the time text to be parsed.
text
,
int
where to start parsing.
start
,
int
the index of the pattern character.
patternCharIndex
,
int
the count of a pattern character.
count
,
boolean
if true, then the next field directly abuts this one, and we should use the count to know when to stop parsing.
obeyCount
,
boolean[]
return parameter; upon return, if ambiguousYear[0] is true, then a two-digit year was parsed and may need to be readjusted.
ambiguousYear
,
ParsePosition
origPos.errorIndex is used to return an error index at which a parse error occurred, if matching failure occurs.
origPos
,
boolean useFollowingMinusSignAsDelimiter, CalendarBuilder calb)

Private member function that converts the parsed date strings into timeFields.

private int

Returns:

updated parsed position, or its negative value to indicate a parsing error
subParseNumericZone
(String
the text to be parsed
text
,
int
the character position to start parsing
start
,
int
1: positive; -1: negative
sign
,
int
0: 'Z' or "GMT+hh:mm" parsing; 1 - 3: the number of 'X's
count
,
boolean
true - colon required between hh and mm; false - no colon required
colon
,
CalendarBuilder
a CalendarBuilder in which the parsed value is stored
calb
)

Parses numeric forms of time zone offset, such as "hh:mm", and sets calb to the parsed value.

private int
subParseZoneString(String text, int start, CalendarBuilder calb)

find time zone 'text' matched zoneStrings and set to internal calendar.

public String

Returns:

a localized pattern string describing this date format.
toLocalizedPattern
()

Returns a localized pattern string describing this date format.

public String

Returns:

a pattern string describing this date format.
toPattern
()

Returns a pattern string describing this date format.

public String

Returns:

a string identifying this SimpleDateFormat, for debugging
toString
()

Overrides java.lang.Object.toString.

Returns a string identifying this SimpleDateFormat, for debugging.

private String
translatePattern(String pattern, String from, String to)

Translates a pattern, mapping each character in the from string to the corresponding character in the to string.

private boolean
useDateFormatSymbols()

Returns true if the DateFormatSymbols has been set explicitly or locale is null.

private void
zeroPaddingNumber(int value, int minDigits, int maxDigits, Format.StringBuf buffer)

Formats a number with the specified minimum and maximum number of digits.

Inherited from java.text.DateFormat:
formatformatformatgetAvailableLocalesgetCalendargetDateInstancegetDateInstancegetDateInstancegetDateTimeInstancegetDateTimeInstancegetDateTimeInstancegetInstancegetNumberFormatgetTimeInstancegetTimeInstancegetTimeInstancegetTimeZoneisLenientparseparseObjectsetCalendarsetLenientsetNumberFormatsetTimeZone

Field Detail

cachedNumberFormatDataback to summary
private static final ConcurrentMap<Locale, NumberFormat> cachedNumberFormatData

Cache NumberFormat instances with Locale key.

compiledPatternback to summary
private transient char[] compiledPattern

The compiled pattern.

currentSerialVersionback to summary
pack-priv static final int currentSerialVersion
defaultCenturyStartback to summary
private Date defaultCenturyStart

We map dates with two-digit years into the century starting at defaultCenturyStart, which may be any date. May not be null.

Since
1.1.4
defaultCenturyStartYearback to summary
private transient int defaultCenturyStartYear
forceStandaloneFormback to summary
private transient boolean forceStandaloneForm

True if standalone form needs to be used.

formatDataback to summary
private DateFormatSymbols formatData

The symbols used by this formatter for week names, month names, etc. May not be null.

See Also
java.text.DateFormatSymbols
GMTback to summary
private static final String GMT
hasFollowingMinusSignback to summary
private transient boolean hasFollowingMinusSign

True when a negative sign follows a number. (True as default in Arabic.)

localeback to summary
private Locale locale

The Locale used to instantiate this SimpleDateFormat. The value may be null if this object has been created by an older SimpleDateFormat and deserialized.

Since
1.6
MILLIS_PER_MINUTEback to summary
private static final int MILLIS_PER_MINUTE
minusSignback to summary
private transient char minusSign

The minus sign to be used with format and parse.

originalNumberFormatback to summary
private transient NumberFormat originalNumberFormat

Saved numberFormat and pattern.

See Also
SimpleDateFormat#checkNegativeNumberExpression
originalNumberPatternback to summary
private transient String originalNumberPattern
patternback to summary
private String pattern

The pattern string of this formatter. This is always a non-localized pattern. May not be null. See class documentation for details.

PATTERN_INDEX_TO_CALENDAR_FIELDback to summary
private static final int[] PATTERN_INDEX_TO_CALENDAR_FIELD
PATTERN_INDEX_TO_DATE_FORMAT_FIELDback to summary
private static final int[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD
PATTERN_INDEX_TO_DATE_FORMAT_FIELD_IDback to summary
private static final DateFormat.Field[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID
REST_OF_STYLESback to summary
private static final int[] REST_OF_STYLES
serialVersionOnStreamback to summary
private int serialVersionOnStream

The version of the serialized data on the stream. Possible values:

  • 0 or not present on stream: JDK 1.1.3. This version has no defaultCenturyStart on stream.
  • 1 JDK 1.1.4 or later. This version adds defaultCenturyStart.
When streaming out this class, the most recent format and the highest allowable serialVersionOnStream is written.
Since
1.1.4
serialVersionUIDback to summary
pack-priv static final long serialVersionUID

Hides java.text.DateFormat.serialVersionUID.

Annotations
@Serial
TAG_QUOTE_ASCII_CHARback to summary
private static final int TAG_QUOTE_ASCII_CHAR

Tags for the compiled pattern.

TAG_QUOTE_CHARSback to summary
private static final int TAG_QUOTE_CHARS
useDateFormatSymbolsback to summary
pack-priv transient boolean useDateFormatSymbols

Indicates whether this SimpleDateFormat should use the DateFormatSymbols. If true, the format and parse methods use the DateFormatSymbols values. If false, the format and parse methods call Calendar.getDisplayName or Calendar.getDisplayNames.

zeroDigitback to summary
private transient char zeroDigit

Locale dependent digit zero.

See Also
zeroPaddingNumber, java.text.DecimalFormatSymbols#getZeroDigit

Constructor Detail

SimpleDateFormatback to summary
public SimpleDateFormat()

Constructs a SimpleDateFormat using the default pattern and date format symbols for the default FORMAT locale

Note

This constructor may not support all locales. For full coverage, use the factory methods in the DateFormat class.

SimpleDateFormatback to summary
public SimpleDateFormat(String pattern)

Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the default FORMAT locale

Note

This constructor may not support all locales. For full coverage, use the factory methods in the DateFormat class.

This is equivalent to calling SimpleDateFormat(pattern, Locale.getDefault(Locale.Category.FORMAT)).

Parameters
pattern:String

the pattern describing the date and time format

Exceptions
NullPointerException:
if the given pattern is null
IllegalArgumentException:
if the given pattern is invalid
See Also
java.util.Locale#getDefault(java.util.Locale.Category), java.util.Locale.Category#FORMAT
SimpleDateFormatback to summary
public SimpleDateFormat(String pattern, Locale locale)

Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the given locale

Note

This constructor may not support all locales. For full coverage, use the factory methods in the DateFormat class.

Parameters
pattern:String

the pattern describing the date and time format

locale:Locale

the locale whose date format symbols should be used

Exceptions
NullPointerException:
if the given pattern or locale is null
IllegalArgumentException:
if the given pattern is invalid
SimpleDateFormatback to summary
public SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)

Constructs a SimpleDateFormat using the given pattern and date format symbols.

Parameters
pattern:String

the pattern describing the date and time format

formatSymbols:DateFormatSymbols

the date format symbols to be used for formatting

Exceptions
NullPointerException:
if the given pattern or formatSymbols is null
IllegalArgumentException:
if the given pattern is invalid

Method Detail

applyLocalizedPatternback to summary
public void applyLocalizedPattern(String pattern)

Applies the given localized pattern string to this date format.

Parameters
pattern:String

a String to be mapped to the new date and time format pattern for this format

Exceptions
NullPointerException:
if the given pattern is null
IllegalArgumentException:
if the given pattern is invalid
applyPatternback to summary
public void applyPattern(String pattern)

Applies the given pattern string to this date format.

Parameters
pattern:String

the new date and time pattern for this date format

Exceptions
NullPointerException:
if the given pattern is null
IllegalArgumentException:
if the given pattern is invalid
applyPatternImplback to summary
private void applyPatternImpl(String pattern)
charEqualsback to summary
private boolean charEquals(char ch1, char ch2)
checkNegativeNumberExpressionback to summary
private void checkNegativeNumberExpression()

Analyze the negative subpattern of DecimalFormat and set/update values as necessary.

cloneback to summary
public Object clone()

Overrides java.text.DateFormat.clone.

Creates a copy of this SimpleDateFormat. This also clones the format's date format symbols.

Returns:Object

a clone of this SimpleDateFormat

Annotations
@Override
compileback to summary
private char[] compile(String pattern)

Returns the compiled form of the given pattern. The syntax of the compiled pattern is:

CompiledPattern: EntryList EntryList: Entry EntryList Entry Entry: TagField TagField data TagField: Tag Length TaggedData Tag: pattern_char_index TAG_QUOTE_CHARS Length: short_length long_length TaggedData: TAG_QUOTE_ASCII_CHAR ascii_char
where `short_length' is an 8-bit unsigned integer between 0 and 254. `long_length' is a sequence of an 8-bit integer 255 and a 32-bit signed integer value which is split into upper and lower 16-bit fields in two char's. `pattern_char_index' is an 8-bit integer between 0 and 18. `ascii_char' is an 7-bit ASCII character value. `data' depends on its Tag value.

If Length is short_length, Tag and short_length are packed in a single char, as illustrated below.

char[0] = (Tag << 8) | short_length;
If Length is long_length, Tag and 255 are packed in the first char and a 32-bit integer, as illustrated below.
char[0] = (Tag << 8) | 255; char[1] = (char) (long_length >>> 16); char[2] = (char) (long_length & 0xffff);

If Tag is a pattern_char_index, its Length is the number of pattern characters. For example, if the given pattern is "yyyy", Tag is 1 and Length is 4, followed by no data.

If Tag is TAG_QUOTE_CHARS, its Length is the number of char's following the TagField. For example, if the given pattern is "'o''clock'", Length is 7 followed by a char sequence of o&nbs;'&nbs;c&nbs;l&nbs;o&nbs;c&nbs;k.

TAG_QUOTE_ASCII_CHAR is a special tag and has an ASCII character in place of Length. For example, if the given pattern is "'o'", the TaggedData entry is ((TAG_QUOTE_ASCII_CHAR&nbs;<<&nbs;8)&nbs;|&nbs;'o').

Exceptions
NullPointerException:
if the given pattern is null
IllegalArgumentException:
if the given pattern is invalid
encodeback to summary
private static void encode(int tag, int length, StringBuilder buffer)

Encodes the given tag and length and puts encoded char(s) into buffer.

equalsback to summary
public boolean equals(Object obj)

Overrides java.text.DateFormat.equals.

Compares the specified object with this SimpleDateFormat for equality. Returns true if the object is also a SimpleDateFormat and the two formats would format any value the same.

Implementation Specification

This method performs an equality check with a notion of class identity based on getClass(), rather than instanceof. Therefore, in the equals methods in subclasses, no instance of this class should compare as equal to an instance of a subclass.

Parameters
obj:Object

object to be compared for equality

Returns:boolean

true if the specified object is equal to this SimpleDateFormat

Annotations
@Override
See Also
Object#equals(Object)
formatback to summary
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos)

Implements abstract java.text.DateFormat.format.

Formats the given Date into a date/time string and appends the result to the given StringBuffer.

Parameters
date:Date

the date-time value to be formatted into a date-time string.

toAppendTo:StringBuffer

where the new date-time text is to be appended.

pos:FieldPosition

keeps track on the position of the field within the returned string. For example, given a date-time text "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition is DateFormat#YEAR_FIELD, the begin index and end index of fieldPosition will be set to 0 and 4, respectively. Notice that if the same date-time field appears more than once in a pattern, the fieldPosition will be set for the first occurrence of that date-time field. For instance, formatting a Date to the date-time string "1 PM PDT (Pacific Daylight Time)" using the pattern "h a z (zzzz)" and the alignment field DateFormat#TIMEZONE_FIELD, the begin index and end index of fieldPosition will be set to 5 and 8, respectively, for the first occurrence of the timezone pattern character 'z'.

Returns:StringBuffer

the formatted date-time string.

Annotations
@Override
Exceptions
NullPointerException:
if any of the parameters is null.
formatback to summary
pack-priv final Format.StringBuf format(Date date, Format.StringBuf toAppendTo, FieldPosition pos)

Overrides java.text.DateFormat.format.

Annotations
@Override
formatback to summary
private Format.StringBuf format(Date date, Format.StringBuf toAppendTo, Format.FieldDelegate delegate)
formatToCharacterIteratorback to summary
public AttributedCharacterIterator formatToCharacterIterator(Object obj)

Overrides java.text.Format.formatToCharacterIterator.

Formats an Object producing an AttributedCharacterIterator. You can use the returned AttributedCharacterIterator to build the resulting String, as well as to determine information about the resulting String.

Each attribute key of the AttributedCharacterIterator will be of type DateFormat.Field, with the corresponding attribute value being the same as the attribute key.

Parameters
obj:Object

The object to format

Returns:AttributedCharacterIterator

AttributedCharacterIterator describing the formatted value.

Annotations
@Override
Exceptions
NullPointerException:
if obj is null.
IllegalArgumentException:
if the Format cannot format the given object, or if the Format's pattern string is invalid.
Since
1.4
get2DigitYearStartback to summary
public Date get2DigitYearStart()

Returns the beginning date of the 100-year period 2-digit years are interpreted as being within.

Returns:Date

the start of the 100-year period into which two digit years are parsed

Since
1.2
See Also
set2DigitYearStart
getDateFormatSymbolsback to summary
public DateFormatSymbols getDateFormatSymbols()

Gets a copy of the date and time format symbols of this date format.

Returns:DateFormatSymbols

the date and time format symbols of this date format

See Also
setDateFormatSymbols
getDisplayContextNamesMapback to summary
private Map<String, Integer> getDisplayContextNamesMap(int field, Locale locale)

Obtains display names map, taking the context into account. Currently only the month name pattern 'M' is context dependent.

getDisplayNamesMapback to summary
private Map<String, Integer> getDisplayNamesMap(int field, Locale locale)
hashCodeback to summary
public int hashCode()

Overrides java.text.DateFormat.hashCode.

Returns the hash code value for this SimpleDateFormat.

Implementation Specification

This method calculates the hash code value using the value returned by toPattern().

Returns:int

the hash code value for this SimpleDateFormat

Annotations
@Override
See Also
Object#hashCode()
initializeback to summary
private void initialize(Locale loc)
initializeCalendarback to summary
private void initializeCalendar(Locale loc)
initializeDefaultCenturyback to summary
private void initializeDefaultCentury()
isDigitback to summary
private boolean isDigit(char c)
matchDSTStringback to summary
private boolean matchDSTString(String text, int start, int zoneIndex, int standardIndex, String[][] zoneStrings)
matchStringback to summary
private int matchString(String text, int start, int field, String[] data, CalendarBuilder calb)

Private code-size reduction function used by subParse.

Parameters
text:String

the time text being parsed.

start:int

where to start parsing.

field:int

the date field being parsed.

data:String[]

the string array to parsed.

Returns:int

the new start position if matching succeeded; a negative number indicating matching failure, otherwise.

matchStringback to summary
private int matchString(String text, int start, int field, Map<String, Integer> data, CalendarBuilder calb)

Performs the same thing as matchString(String, int, int, String[]). This method takes a Map instead of String[].

matchZoneStringback to summary
private int matchZoneString(String text, int start, String[] zoneNames)
parseback to summary
public Date parse(String text, ParsePosition pos)

Implements abstract java.text.DateFormat.parse.

Parses text from a string to produce a Date.

The method attempts to parse text starting at the index given by pos. If parsing succeeds, then the index of pos is updated to the index after the last character used (parsing does not necessarily use all characters up to the end of the string), and the parsed date is returned. The updated pos can be used to indicate the starting point for the next call to this method. If an error occurs, then the index of pos is not changed, the error index of pos is set to the index of the character where the error occurred, and null is returned.

This parsing operation uses the calendar to produce a Date. All of the calendar's date-time fields are cleared before parsing, and the calendar's default values of the date-time fields are used for any missing date-time information. For example, the year value of the parsed Date is 1970 with GregorianCalendar if no year value is given from the parsing operation. The TimeZone value may be overwritten, depending on the given pattern and the time zone value in text. Any TimeZone value that has previously been set by a call to setTimeZone may need to be restored for further operations.

Parameters
text:String

A String, part of which should be parsed.

pos:ParsePosition

A ParsePosition object with index and error index information as described above.

Returns:Date

A Date parsed from the string. In case of error, returns null.

Annotations
@Override
Exceptions
NullPointerException:
if text or pos is null.
parseAmbiguousDatesAsAfterback to summary
private void parseAmbiguousDatesAsAfter(Date startDate)
readObjectback to summary
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException

After reading an object from the input stream, the format pattern in the object is verified.

Annotations
@Serial
Exceptions
InvalidObjectException:
if the pattern is invalid
set2DigitYearStartback to summary
public void set2DigitYearStart(Date startDate)

Sets the 100-year period 2-digit years will be interpreted as being in to begin on the date the user specifies.

Parameters
startDate:Date

During parsing, two digit years will be placed in the range startDate to startDate + 100 years.

Exceptions
NullPointerException:
if startDate is null.
Since
1.2
See Also
get2DigitYearStart
setDateFormatSymbolsback to summary
public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols)

Sets the date and time format symbols of this date format.

Parameters
newFormatSymbols:DateFormatSymbols

the new date and time format symbols

Exceptions
NullPointerException:
if the given newFormatSymbols is null
See Also
getDateFormatSymbols
shouldObeyCountback to summary
private boolean shouldObeyCount(int tag, int count)
subFormatback to summary
private void subFormat(int patternCharIndex, int count, Format.FieldDelegate delegate, Format.StringBuf buffer, boolean useDateFormatSymbols)

Private member function that does the real date/time formatting.

subParseback to summary
private int subParse(String text, int start, int patternCharIndex, int count, boolean obeyCount, boolean[] ambiguousYear, ParsePosition origPos, boolean useFollowingMinusSignAsDelimiter, CalendarBuilder calb)

Private member function that converts the parsed date strings into timeFields. Returns -start (for ParsePosition) if failed.

Parameters
text:String

the time text to be parsed.

start:int

where to start parsing.

patternCharIndex:int

the index of the pattern character.

count:int

the count of a pattern character.

obeyCount:boolean

if true, then the next field directly abuts this one, and we should use the count to know when to stop parsing.

ambiguousYear:boolean[]

return parameter; upon return, if ambiguousYear[0] is true, then a two-digit year was parsed and may need to be readjusted.

origPos:ParsePosition

origPos.errorIndex is used to return an error index at which a parse error occurred, if matching failure occurs.

Returns:int

the new start position if matching succeeded; -1 indicating matching failure, otherwise. In case matching failure occurred, an error index is set to origPos.errorIndex.

subParseNumericZoneback to summary
private int subParseNumericZone(String text, int start, int sign, int count, boolean colon, CalendarBuilder calb)

Parses numeric forms of time zone offset, such as "hh:mm", and sets calb to the parsed value.

Parameters
text:String

the text to be parsed

start:int

the character position to start parsing

sign:int

1: positive; -1: negative

count:int

0: 'Z' or "GMT+hh:mm" parsing; 1 - 3: the number of 'X's

colon:boolean

true - colon required between hh and mm; false - no colon required

calb:CalendarBuilder

a CalendarBuilder in which the parsed value is stored

Returns:int

updated parsed position, or its negative value to indicate a parsing error

subParseZoneStringback to summary
private int subParseZoneString(String text, int start, CalendarBuilder calb)

find time zone 'text' matched zoneStrings and set to internal calendar.

toLocalizedPatternback to summary
public String toLocalizedPattern()

Returns a localized pattern string describing this date format.

Returns:String

a localized pattern string describing this date format.

toPatternback to summary
public String toPattern()

Returns a pattern string describing this date format.

Returns:String

a pattern string describing this date format.

toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Returns a string identifying this SimpleDateFormat, for debugging.

Returns:String

a string identifying this SimpleDateFormat, for debugging

Annotations
@Override
translatePatternback to summary
private String translatePattern(String pattern, String from, String to)

Translates a pattern, mapping each character in the from string to the corresponding character in the to string.

Exceptions
IllegalArgumentException:
if the given pattern is invalid
useDateFormatSymbolsback to summary
private boolean useDateFormatSymbols()

Returns true if the DateFormatSymbols has been set explicitly or locale is null.

zeroPaddingNumberback to summary
private void zeroPaddingNumber(int value, int minDigits, int maxDigits, Format.StringBuf buffer)

Formats a number with the specified minimum and maximum number of digits.