Class SimpleDateFormat
- All Implemented Interfaces:
Serializable,Cloneable
public class SimpleDateFormat extends DateFormat
Date into
a String, and parsing turns a String into a Date.
Time Pattern Syntax
You can supply a Unicode UTS #35
pattern describing what strings are produced/accepted, but almost all
callers should use DateFormat.getDateInstance(), DateFormat.getDateTimeInstance(),
or DateFormat.getTimeInstance() to get a ready-made instance suitable for the user's
locale. In cases where the system does not provide a suitable pattern, see
android.text.format.DateFormat#getBestDateTimePattern which lets you specify
the elements you'd like in a pattern and get back a pattern suitable for any given locale.
The main reason you'd create an instance this class directly is because you need to
format/parse a specific machine-readable format, in which case you almost certainly want
to explicitly ask for Locale.US to ensure that you get ASCII digits (rather than,
say, Arabic digits).
(See "Be wary of the default locale".)
The most useful non-localized pattern is "yyyy-MM-dd HH:mm:ss.SSSZ", which corresponds
to the ISO 8601 international standard date format.
To specify the time format, use a time pattern string. In this
string, any character from 'A' to 'Z' or 'a' to 'z' is
treated specially. All other characters are passed through verbatim. The interpretation of each
of the ASCII letters is given in the table below. ASCII letters not appearing in the table are
reserved for future use, and it is an error to attempt to use them.
The number of consecutive copies (the "count") of a pattern character further influences the format, as shown in the table. For fields of kind "number", the count is the minimum number of digits; shorter values are zero-padded to the given width and longer values overflow it.
| Symbol | Meaning | Kind | Example |
D | day in year | (Number) | 189 |
E | day of week | (Text) | E/EE/EEE:Tue, EEEE:Tuesday, EEEEE:T |
F | day of week in month | (Number) | 2 (2nd Wed in July) |
G | era designator | (Text) | AD |
H | hour in day (0-23) | (Number) | 0 |
K | hour in am/pm (0-11) | (Number) | 0 |
L | stand-alone month | (Text) | L:1 LL:01 LLL:Jan LLLL:January LLLLL:J |
M | month in year | (Text) | M:1 MM:01 MMM:Jan MMMM:January MMMMM:J |
S | fractional seconds | (Number) | 978 |
W | week in month | (Number) | 2 |
Z | time zone (RFC 822) | (Time Zone) | Z/ZZ/ZZZ:-0800 ZZZZ:GMT-08:00 ZZZZZ:-08:00 |
a | am/pm marker | (Text) | PM |
c | stand-alone day of week | (Text) | c/cc/ccc:Tue, cccc:Tuesday, ccccc:T |
d | day in month | (Number) | 10 |
h | hour in am/pm (1-12) | (Number) | 12 |
k | hour in day (1-24) | (Number) | 24 |
m | minute in hour | (Number) | 30 |
s | second in minute | (Number) | 55 |
w | week in year | (Number) | 27 |
y | year | (Number) | yy:10 y/yyy/yyyy:2010 |
z | time zone | (Time Zone) | z/zz/zzz:PST zzzz:Pacific Standard Time |
' | escape for text | (Delimiter) | 'Date=':Date= |
'' | single quote | (Literal) | 'o''clock':o'clock |
Fractional seconds are handled specially: they're zero-padded on the right.
The two pattern characters L and c are ICU-compatible extensions, not
available in the RI or in Android before Android 2.3 (Gingerbread, API level 9). These
extensions are necessary for correct localization in languages such as Russian
that make a grammatical distinction between, say, the word "June" in the sentence "June" and
in the sentence "June 10th"; the former is the stand-alone form, the latter the regular
form (because the usual case is to format a complete date). The relationship between E
and c is equivalent, but for weekday names.
Five-count patterns (such as "MMMMM") used for the shortest non-numeric representation of a field were introduced in Android 4.3 (Jelly Bean MR2, API level 18).
When two numeric fields are directly adjacent with no intervening delimiter characters, they constitute a run of adjacent numeric fields. Such runs are parsed specially. For example, the format "HHmmss" parses the input text "123456" to 12:34:56, parses the input text "12345" to 1:23:45, and fails to parse "1234". In other words, the leftmost field of the run is flexible, while the others keep a fixed width. If the parse fails anywhere in the run, then the leftmost field is shortened by one character, and the entire run is parsed again. This is repeated until either the parse succeeds or the leftmost field is one character in length. If the parse still fails at that point, the parse of the run fails.
See set2DigitYearStart(java.util.Date) for more about handling two-digit years.
Sample Code
If you're formatting for human use, you should use an instance returned from
DateFormat as described above. This code:
DateFormat[] formats = new DateFormat[] {
DateFormat.getDateInstance(),
DateFormat.getDateTimeInstance(),
DateFormat.getTimeInstance(),
};
for (DateFormat df : formats) {
System.out.println(df.format(new Date(0)));
}
Produces this output when run on an en_US device in the America/Los_Angeles time zone:
Dec 31, 1969 Dec 31, 1969 4:00:00 PM 4:00:00 PMAnd will produce similarly appropriate localized human-readable output on any user's system.
If you're formatting for machine use, consider this code:
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.out.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.format("%30s %s\n", format, sdf.format(new Date(0)));
}
Which produces this output when run in the America/Los_Angeles time zone:
yyyy-MM-dd 1969-12-31
yyyy-MM-dd 1970-01-01
yyyy-MM-dd HH:mm 1969-12-31 16:00
yyyy-MM-dd HH:mm 1970-01-01 00:00
yyyy-MM-dd HH:mmZ 1969-12-31 16:00-0800
yyyy-MM-dd HH:mmZ 1970-01-01 00:00+0000
yyyy-MM-dd HH:mm:ss.SSSZ 1969-12-31 16:00:00.000-0800
yyyy-MM-dd HH:mm:ss.SSSZ 1970-01-01 00:00:00.000+0000
yyyy-MM-dd'T'HH:mm:ss.SSSZ 1969-12-31T16:00:00.000-0800
yyyy-MM-dd'T'HH:mm:ss.SSSZ 1970-01-01T00:00:00.000+0000
As this example shows, each SimpleDateFormat instance has a TimeZone.
This is because it's called upon to format instances of Date, which represents an
absolute time in UTC. That is, Date does not carry time zone information.
By default, SimpleDateFormat will use the system's default time zone. This is
appropriate for human-readable output (for which, see the previous sample instead), but
generally inappropriate for machine-readable output, where ambiguity is a problem. Note that
in this example, the output that included a time but no time zone cannot be parsed back into
the original Date. For this
reason it is almost always necessary and desirable to include the timezone in the output.
It may also be desirable to set the formatter's time zone to UTC (to ease comparison, or to
make logs more readable, for example). It is often best to avoid formatting completely when
writing dates/times in machine-readable form. Simply sending the "Unix time" as a long
or as the string corresponding to the long is cheaper and unambiguous, and can be formatted any
way the recipient deems appropriate.
Synchronization
SimpleDateFormat is not thread-safe. Users should create a separate instance for
each thread.- See Also:
Calendar,Date,TimeZone,DateFormat, Serialized Form
-
Nested Class Summary
Nested classes/interfaces inherited from class java.text.DateFormat
DateFormat.Field -
Field Summary
Fields inherited from class java.text.DateFormat
AM_PM_FIELD, calendar, DATE_FIELD, DAY_OF_WEEK_FIELD, DAY_OF_WEEK_IN_MONTH_FIELD, DAY_OF_YEAR_FIELD, DEFAULT, ERA_FIELD, FULL, HOUR_OF_DAY0_FIELD, HOUR_OF_DAY1_FIELD, HOUR0_FIELD, HOUR1_FIELD, LONG, MEDIUM, MILLISECOND_FIELD, MINUTE_FIELD, MONTH_FIELD, numberFormat, SECOND_FIELD, SHORT, TIMEZONE_FIELD, WEEK_OF_MONTH_FIELD, WEEK_OF_YEAR_FIELD, YEAR_FIELD -
Constructor Summary
Constructors Constructor Description SimpleDateFormat()Constructs a newSimpleDateFormatfor formatting and parsing dates and times in theSHORTstyle for the user's default locale.SimpleDateFormat(String pattern)Constructs a newSimpleDateFormatusing the specified non-localized pattern and theDateFormatSymbolsandCalendarfor the user's default locale.SimpleDateFormat(String template, DateFormatSymbols value)Constructs a newSimpleDateFormatusing the specified non-localized pattern andDateFormatSymbolsand theCalendarfor the user's default locale.SimpleDateFormat(String template, Locale locale)Constructs a newSimpleDateFormatusing the specified non-localized pattern and theDateFormatSymbolsandCalendarfor the specified locale. -
Method Summary
Modifier and Type Method Description voidapplyLocalizedPattern(String template)Changes the pattern of this simple date format to the specified pattern which uses localized pattern characters.voidapplyPattern(String template)Changes the pattern of this simple date format to the specified pattern which uses non-localized pattern characters.Objectclone()Returns a newSimpleDateFormatwith the same pattern and properties as this simple date format.booleanequals(Object object)Compares the specified object with this simple date format and indicates if they are equal.StringBufferformat(Date date, StringBuffer buffer, FieldPosition fieldPos)Formats the specified date as a string using the pattern of this date format and appends the string to the specified string buffer.AttributedCharacterIteratorformatToCharacterIterator(Object object)Formats the specified object using the rules of this simple date format and returns anAttributedCharacterIteratorwith the formatted date and attributes.Dateget2DigitYearStart()Returns the date which is the start of the one hundred year period for two-digit year values.DateFormatSymbolsgetDateFormatSymbols()Returns theDateFormatSymbolsused by this simple date format.inthashCode()Returns an integer hash code for this object.Dateparse(String string, ParsePosition position)Parses a date from the specified string starting at the index specified byposition.voidset2DigitYearStart(Date date)Sets the date which is the start of the one hundred year period for two-digit year values.voidsetDateFormatSymbols(DateFormatSymbols value)Sets theDateFormatSymbolsused by this simple date format.StringtoLocalizedPattern()Returns the pattern of this simple date format using localized pattern characters.StringtoPattern()Returns the pattern of this simple date format using non-localized pattern characters.Methods inherited from class java.text.DateFormat
format, format, getAvailableLocales, getCalendar, getDateInstance, getDateInstance, getDateInstance, getDateTimeInstance, getDateTimeInstance, getDateTimeInstance, getInstance, getNumberFormat, getTimeInstance, getTimeInstance, getTimeInstance, getTimeZone, isLenient, parse, parseObject, setCalendar, setLenient, setNumberFormat, setTimeZoneMethods inherited from class java.text.Format
format, parseObject
-
Constructor Details
-
SimpleDateFormat
public SimpleDateFormat()Constructs a newSimpleDateFormatfor formatting and parsing dates and times in theSHORTstyle for the user's default locale. See "Be wary of the default locale". -
SimpleDateFormat
Constructs a newSimpleDateFormatusing the specified non-localized pattern and theDateFormatSymbolsandCalendarfor the user's default locale. See "Be wary of the default locale".- Parameters:
pattern- the pattern.- Throws:
NullPointerException- if the pattern isnull.IllegalArgumentException- ifpatternis not considered to be usable by this formatter.
-
SimpleDateFormat
Constructs a newSimpleDateFormatusing the specified non-localized pattern andDateFormatSymbolsand theCalendarfor the user's default locale. See "Be wary of the default locale".- Parameters:
template- the pattern.value- the DateFormatSymbols.- Throws:
NullPointerException- if the pattern isnull.IllegalArgumentException- if the pattern is invalid.
-
SimpleDateFormat
Constructs a newSimpleDateFormatusing the specified non-localized pattern and theDateFormatSymbolsandCalendarfor the specified locale.- Parameters:
template- the pattern.locale- the locale.- Throws:
NullPointerException- if the pattern isnull.IllegalArgumentException- if the pattern is invalid.
-
-
Method Details
-
applyLocalizedPattern
Changes the pattern of this simple date format to the specified pattern which uses localized pattern characters.- Parameters:
template- the localized pattern.
-
applyPattern
Changes the pattern of this simple date format to the specified pattern which uses non-localized pattern characters.- Parameters:
template- the non-localized pattern.- Throws:
NullPointerException- if the pattern isnull.IllegalArgumentException- if the pattern is invalid.
-
clone
Returns a newSimpleDateFormatwith the same pattern and properties as this simple date format.- Overrides:
clonein classDateFormat- Returns:
- a shallow copy of this format.
- See Also:
Cloneable
-
equals
Compares the specified object with this simple date format and indicates if they are equal. In order to be equal,objectmust be an instance ofSimpleDateFormatand have the sameDateFormatproperties, pattern,DateFormatSymbolsand creation year.- Overrides:
equalsin classDateFormat- Parameters:
object- the object to compare with this object.- Returns:
trueif the specified object is equal to this simple date format;falseotherwise.- See Also:
hashCode()
-
formatToCharacterIterator
Formats the specified object using the rules of this simple date format and returns anAttributedCharacterIteratorwith the formatted date and attributes.- Overrides:
formatToCharacterIteratorin classFormat- Parameters:
object- the object to format.- Returns:
- an
AttributedCharacterIteratorwith the formatted date and attributes. - Throws:
NullPointerException- if the object isnull.IllegalArgumentException- if the object cannot be formatted by this simple date format.
-
format
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
fieldmember offieldcontains a value specifying a format field, then itsbeginIndexandendIndexmembers will be updated with the position of the first occurrence of this field in the formatted text.- Specified by:
formatin classDateFormat- Parameters:
date- the date to format.buffer- the target string buffer to append the formatted date/time to.fieldPos- on input: an optional alignment field; on output: the offsets of the alignment field in the formatted text.- Returns:
- the string buffer.
- Throws:
IllegalArgumentException- if there are invalid characters in the pattern.
-
get2DigitYearStart
Returns the date which is the start of the one hundred year period for two-digit year values. Seeset2DigitYearStart(java.util.Date)for details. -
getDateFormatSymbols
Returns theDateFormatSymbolsused by this simple date format.- Returns:
- the
DateFormatSymbolsobject.
-
hashCode
public int hashCode()Description copied from class:ObjectReturns an integer hash code for this object. By contract, any two objects for whichObject.equals(java.lang.Object)returnstruemust return the same hash code value. This means that subclasses ofObjectusually override both methods or neither method.Note that hash values must not change over time unless information used in equals comparisons also changes.
See Writing a correct
hashCodemethod if you intend implementing your ownhashCodemethod.- Overrides:
hashCodein classDateFormat- Returns:
- this object's hash code.
- See Also:
Object.equals(java.lang.Object)
-
parse
Parses a date from the specified string starting at the index specified byposition. If the string is successfully parsed then the index of theParsePositionis updated to the index following the parsed text. On error, the index is unchanged and the error index ofParsePositionis set to the index where the error occurred.- Specified by:
parsein classDateFormat- Parameters:
string- the string to parse using the pattern of this simple date format.position- input/output parameter, specifies the start index instringfrom 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.- Returns:
- the date resulting from the parse, or
nullif there is an error. - Throws:
IllegalArgumentException- if there are invalid characters in the pattern.
-
set2DigitYearStart
Sets the date which is the start of the one hundred year period for two-digit year values.When parsing a date string using the abbreviated year pattern
yy,SimpleDateFormatmust interpret the abbreviated year relative to some century. It does this by adjusting dates to be within 80 years before and 20 years after the time theSimpleDateFormatinstance was created. For example, using a pattern ofMM/dd/yy, an instance created on Jan 1, 1997 would interpret the string"01/11/12"as Jan 11, 2012 but interpret the string"05/04/64"as May 4, 1964. During parsing, only strings consisting of exactly two digits, as defined byCharacter.isDigit(char), will be parsed into the default century. Any other numeric string, such as a one digit string, a three or more digit string, or a two digit string that isn't all digits (for example,"-1"), is interpreted literally. So using the same pattern, both"01/02/3"and"01/02/003"are parsed as Jan 2, 3 AD. Similarly,"01/02/-3"is parsed as Jan 2, 4 BC.If the year pattern does not have exactly two 'y' characters, the year is interpreted literally, regardless of the number of digits. So using the pattern
MM/dd/yyyy,"01/11/12"is parsed as Jan 11, 12 A.D. -
setDateFormatSymbols
Sets theDateFormatSymbolsused by this simple date format.- Parameters:
value- the newDateFormatSymbolsobject.
-
toLocalizedPattern
Returns the pattern of this simple date format using localized pattern characters.- Returns:
- the localized pattern.
-
toPattern
Returns the pattern of this simple date format using non-localized pattern characters.- Returns:
- the non-localized pattern.
-