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' are reserved):

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
M Month in year 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 in week Text Tuesday; Tue
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
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.
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

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.

@version
1.77, 01/22/04
@author
Mark Davis, Chen-Lieh Huang, Alan Liu
Constructs a SimpleDateFormat using the default pattern and date format symbols for the default locale. Note: This constructor may not support all locales. For full coverage, use the factory methods in the DateFormat class.
Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the default locale. Note: This constructor may not support all locales. For full coverage, use the factory methods in the DateFormat class.
Parameters
patternthe pattern describing the date and time format
Throws
NullPointerExceptionif the given pattern is null
IllegalArgumentExceptionif the given pattern is invalid
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
patternthe pattern describing the date and time format
localethe locale whose date format symbols should be used
Throws
NullPointerExceptionif the given pattern is null
IllegalArgumentExceptionif the given pattern is invalid
Constructs a SimpleDateFormat using the given pattern and date format symbols.
Parameters
patternthe pattern describing the date and time format
formatSymbolsthe date format symbols to be used for formatting
Throws
NullPointerExceptionif the given pattern or formatSymbols is null
IllegalArgumentExceptionif the given pattern is invalid
Useful constant for AM_PM field alignment. Used in FieldPosition of date/time formatting.
Useful constant for DATE field alignment. Used in FieldPosition of date/time formatting.
Useful constant for DAY_OF_WEEK field alignment. Used in FieldPosition of date/time formatting.
Useful constant for DAY_OF_WEEK_IN_MONTH field alignment. Used in FieldPosition of date/time formatting.
Useful constant for DAY_OF_YEAR field alignment. Used in FieldPosition of date/time formatting.
Constant for default style pattern. Its value is MEDIUM.
Useful constant for ERA field alignment. Used in FieldPosition of date/time formatting.
Constant for full style pattern.
Useful constant for zero-based HOUR_OF_DAY field alignment. Used in FieldPosition of date/time formatting. HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock. For example, 23:59 + 01:00 results in 00:59.
Useful constant for one-based HOUR_OF_DAY field alignment. Used in FieldPosition of date/time formatting. HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock. For example, 23:59 + 01:00 results in 24:59.
Useful constant for zero-based HOUR field alignment. Used in FieldPosition of date/time formatting. HOUR0_FIELD is used for the zero-based 12-hour clock. For example, 11:30 PM + 1 hour results in 00:30 AM.
Useful constant for one-based HOUR field alignment. Used in FieldPosition of date/time formatting. HOUR1_FIELD is used for the one-based 12-hour clock. For example, 11:30 PM + 1 hour results in 12:30 AM.
Constant for long style pattern.
Constant for medium style pattern.
Useful constant for MILLISECOND field alignment. Used in FieldPosition of date/time formatting.
Useful constant for MINUTE field alignment. Used in FieldPosition of date/time formatting.
Useful constant for MONTH field alignment. Used in FieldPosition of date/time formatting.
Useful constant for SECOND field alignment. Used in FieldPosition of date/time formatting.
Constant for short style pattern.
Useful constant for TIMEZONE field alignment. Used in FieldPosition of date/time formatting.
Useful constant for WEEK_OF_MONTH field alignment. Used in FieldPosition of date/time formatting.
Useful constant for WEEK_OF_YEAR field alignment. Used in FieldPosition of date/time formatting.
Useful constant for YEAR field alignment. Used in FieldPosition of date/time formatting.
Applies the given localized pattern string to this date format.
Parameters
patterna String to be mapped to the new date and time format pattern for this format
Throws
NullPointerExceptionif the given pattern is null
IllegalArgumentExceptionif the given pattern is invalid
Applies the given pattern string to this date format.
Parameters
patternthe new date and time pattern for this date format
Throws
NullPointerExceptionif the given pattern is null
IllegalArgumentExceptionif the given pattern is invalid
Creates a copy of this SimpleDateFormat. This also clones the format's date format symbols.
Return
a clone of this SimpleDateFormat
Compares the given object with this SimpleDateFormat for equality.
Return
true if the given object is equal to this SimpleDateFormat
Formats a Date into a date/time string.
Parameters
datethe time value to be formatted into a time string.
Return
the formatted time string.
Formats the given Date into a date/time string and appends the result to the given StringBuffer.
Parameters
datethe date-time value to be formatted into a date-time string.
toAppendTowhere the new date-time text is to be appended.
posthe formatting position. On input: an alignment field, if desired. On output: the offsets of the alignment field.
Return
the formatted date-time string.
Throws
NullPointerExceptionif the given date is null
Formats an object to produce a string. This is equivalent to
format (obj, new StringBuffer(), new FieldPosition(0)).toString();
Parameters
objThe object to format
Return
Formatted string.
Throws
IllegalArgumentExceptionif the Format cannot format the given object
Overrides Format. Formats a time object into a time string. Examples of time objects are a time value expressed in milliseconds and a Date object.
Parameters
objmust be a Number or a Date.
toAppendTothe string buffer for the returning time string.
fieldPositionkeeps track of the position of the field within the returned string. On input: an alignment field, if desired. On output: the offsets of the alignment field. For example, given a 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 time field appears more than once in a pattern, the fieldPosition will be set for the first occurrence of that time field. For instance, formatting a Date to the 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'.
Return
the formatted time string.
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
objThe object to format
Return
AttributedCharacterIterator describing the formatted value.
Throws
NullPointerExceptionif obj is null.
IllegalArgumentExceptionif the Format cannot format the given object, or if the Format's pattern string is invalid.
@since
1.4
Returns the beginning date of the 100-year period 2-digit years are interpreted as being within.
Return
the start of the 100-year period into which two digit years are parsed
@since
1.2
Returns an array of all locales for which the get*Instance methods of this class can return localized instances. The array returned must contain at least a Locale instance equal to Locale.US .
Return
An array of locales for which localized DateFormat instances are available.
Gets the calendar associated with this date/time formatter.
Return
the calendar associated with this date/time formatter.
Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Return
The java.lang.Class object that represents the runtime class of the object. The result is of type {@code Class} where X is the erasure of the static type of the expression on which getClass is called.
Gets a copy of the date and time format symbols of this date format.
Return
the date and time format symbols of this date format
Gets the date formatter with the default formatting style for the default locale.
Return
a date formatter.
Gets the date formatter with the given formatting style for the default locale.
Parameters
stylethe given formatting style. For example, SHORT for "M/d/yy" in the US locale.
Return
a date formatter.
Gets the date formatter with the given formatting style for the given locale.
Parameters
stylethe given formatting style. For example, SHORT for "M/d/yy" in the US locale.
aLocalethe given locale.
Return
a date formatter.
Gets the date/time formatter with the default formatting style for the default locale.
Return
a date/time formatter.
Gets the date/time formatter with the given date and time formatting styles for the default locale.
Parameters
dateStylethe given date formatting style. For example, SHORT for "M/d/yy" in the US locale.
timeStylethe given time formatting style. For example, SHORT for "h:mm a" in the US locale.
Return
a date/time formatter.
Gets the date/time formatter with the given formatting styles for the given locale.
Parameters
dateStylethe given date formatting style.
timeStylethe given time formatting style.
aLocalethe given locale.
Return
a date/time formatter.
Get a default date/time formatter that uses the SHORT style for both the date and the time.
Gets the number formatter which this date/time formatter uses to format and parse a time.
Return
the number formatter which this date/time formatter uses.
Gets the time formatter with the default formatting style for the default locale.
Return
a time formatter.
Gets the time formatter with the given formatting style for the default locale.
Parameters
stylethe given formatting style. For example, SHORT for "h:mm a" in the US locale.
Return
a time formatter.
Gets the time formatter with the given formatting style for the given locale.
Parameters
stylethe given formatting style. For example, SHORT for "h:mm a" in the US locale.
aLocalethe given locale.
Return
a time formatter.
Gets the time zone.
Return
the time zone associated with the calendar of DateFormat.
Returns the hash code value for this SimpleDateFormat object.
Return
the hash code value for this SimpleDateFormat object.
Tell whether date/time parsing is to be lenient.
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.

See the method for more information on date parsing.

Parameters
sourceA String whose beginning should be parsed.
Return
A Date parsed from the string.
Throws
ParseExceptionif the beginning of the specified string cannot be parsed.
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.

Parameters
textA String, part of which should be parsed.
posA ParsePosition object with index and error index information as described above.
Return
A Date parsed from the string. In case of error, returns null.
Throws
NullPointerExceptionif text or pos is null.
Parses text from the beginning of the given string to produce an object. The method may not use the entire text of the given string.
Parameters
sourceA String whose beginning should be parsed.
Return
An Object parsed from the string.
Throws
ParseExceptionif the beginning of the specified string cannot be parsed.
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.

See the method for more information on date parsing.

Parameters
sourceA String, part of which should be parsed.
posA ParsePosition object with index and error index information as described above.
Return
A Date parsed from the string. In case of error, returns null.
Throws
NullPointerExceptionif pos is null.
Sets the 100-year period 2-digit years will be interpreted as being in to begin on the date the user specifies.
Parameters
startDateDuring parsing, two digit years will be placed in the range startDate to startDate + 100 years.
@since
1.2
Set the calendar to be used by this date format. Initially, the default calendar for the specified or default locale is used.
Parameters
newCalendarthe new Calendar to be used by the date format
Sets the date and time format symbols of this date format.
Parameters
newFormatSymbolsthe new date and time format symbols
Throws
NullPointerExceptionif the given newFormatSymbols is null
Specify whether or not date/time parsing is to 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.
Parameters
lenientwhen true, parsing is lenient
Allows you to set the number formatter.
Parameters
newNumberFormatthe given new NumberFormat.
Sets the time zone for the calendar of this DateFormat object.
Parameters
zonethe given new time zone.
Returns a localized pattern string describing this date format.
Return
a localized pattern string describing this date format.
Returns a pattern string describing this date format.
Return
a pattern string describing this date format.
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())
 
Return
a string representation of the object.
Causes current thread to wait until another thread invokes the method or the method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Throws
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until either another thread invokes the method or the method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor.

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.
The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout);
         ... // Perform action appropriate to condition
     }
 
(For more information on this topic, see Section 3.2.3 in Doug Lea's "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, 2000), or Item 50 in Joshua Bloch's "Effective Java Programming Language Guide" (Addison-Wesley, 2001).

If the current thread is interrupted by another thread while it is waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

Note that the wait method, as it places the current thread into the wait set for this object, unlocks only this object; any other objects on which the current thread may be synchronized remain locked while the thread waits.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Parameters
timeoutthe maximum time to wait in milliseconds.
Throws
IllegalArgumentExceptionif the value of timeout is negative.
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until another thread invokes the method or the method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. The amount of real time, measured in nanoseconds, is given by:

 1000000*timeout+nanos

In all other respects, this method does the same thing as the method of one argument. In particular, wait(0, 0) means the same thing as wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

  • Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
  • The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.

The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout, nanos);
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Parameters
timeoutthe maximum time to wait in milliseconds.
nanosadditional time, in nanoseconds range 0-999999.
Throws
IllegalArgumentExceptionif the value of timeout is negative or the value of nanos is not in the range 0-999999.
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.