public final class DateTimeFormatter extends Object
This class provides the main application entry point for printing and parsing
and provides common implementations of DateTimeFormatter
:
yyyy-MMM-dd
long
or medium
ISO_LOCAL_DATE
In most cases, provided formatters will be sufficient.
For more complex formatters, a builder
is provided.
The main date-time classes provide two methods - one for printing,
toString(DateTimeFormatter formatter)
, and one for parsing,
parse(CharSequence text, DateTimeFormatter formatter)
.
For example:
String text = date.toString(formatter); LocalDate date = LocalDate.parse(text, formatter);Some aspects of formatting and parsing are dependent on the locale. The locale can be changed using the
withLocale(Locale)
method
which returns a new formatter in the requested locale.
Some applications may need to use the older Format
class for formatting.
The toFormat()
method returns an implementation of the old API.
Modifier and Type | Field and Description |
---|---|
static DateTimeFormatter |
BASIC_ISO_DATE
Returns the ISO date formatter that formats or parses a date without an offset,
such as '20111203'.
|
static DateTimeFormatter |
ISO_DATE
Returns the ISO date formatter that formats or parses a date with the
offset if available, such as '2011-12-03' or '2011-12-03+01:00'.
|
static DateTimeFormatter |
ISO_DATE_TIME
Returns the ISO date formatter that formats or parses a date-time
with the offset and zone if available, such as '2011-12-03T10:15:30',
'2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'.
|
static DateTimeFormatter |
ISO_INSTANT
Returns the ISO instant formatter that formats or parses an instant in UTC.
|
static DateTimeFormatter |
ISO_LOCAL_DATE
Returns the ISO date formatter that formats or parses a date without an offset,
such as '2011-12-03'.
|
static DateTimeFormatter |
ISO_LOCAL_DATE_TIME
Returns the ISO date formatter that formats or parses a date-time
without an offset, such as '2011-12-03T10:15:30'.
|
static DateTimeFormatter |
ISO_LOCAL_TIME
Returns the ISO time formatter that formats or parses a time without an offset,
such as '10:15' or '10:15:30'.
|
static DateTimeFormatter |
ISO_OFFSET_DATE
Returns the ISO date formatter that formats or parses a date with an offset,
such as '2011-12-03+01:00'.
|
static DateTimeFormatter |
ISO_OFFSET_DATE_TIME
Returns the ISO date formatter that formats or parses a date-time
with an offset, such as '2011-12-03T10:15:30+01:00'.
|
static DateTimeFormatter |
ISO_OFFSET_TIME
Returns the ISO time formatter that formats or parses a time with an offset,
such as '10:15+01:00' or '10:15:30+01:00'.
|
static DateTimeFormatter |
ISO_ORDINAL_DATE
Returns the ISO date formatter that formats or parses the ordinal date
without an offset, such as '2012-337'.
|
static DateTimeFormatter |
ISO_TIME
Returns the ISO time formatter that formats or parses a time, with the
offset if available, such as '10:15', '10:15:30' or '10:15:30+01:00'.
|
static DateTimeFormatter |
ISO_WEEK_DATE
Returns the ISO date formatter that formats or parses the week-based date
without an offset, such as '2012-W48-6'.
|
static DateTimeFormatter |
ISO_ZONED_DATE_TIME
Returns the ISO date formatter that formats or parses a date-time with
offset and zone, such as '2011-12-03T10:15:30+01:00[Europe/Paris]'.
|
static DateTimeFormatter |
RFC_1123_DATE_TIME
The RFC-1123 date-time formatter, such as 'Tue, 3 Jun 2008 11:05:30 GMT'.
|
Modifier and Type | Method and Description |
---|---|
String |
format(TemporalAccessor temporal)
Formats a date-time object using this formatter.
|
void |
formatTo(TemporalAccessor temporal,
Appendable appendable)
Formats a date-time object to an
Appendable using this formatter. |
Chronology |
getChronology()
Gets the overriding chronology to be used during formatting.
|
Locale |
getLocale()
Gets the locale to be used during formatting.
|
DateTimeFormatSymbols |
getSymbols()
Gets the set of symbols to be used during formatting.
|
ZoneId |
getZone()
Gets the overriding zone to be used during formatting.
|
static DateTimeFormatter |
ofLocalizedDate(FormatStyle dateStyle)
Returns a locale specific date format.
|
static DateTimeFormatter |
ofLocalizedDateTime(FormatStyle dateTimeStyle)
Returns a locale specific date-time formatter, which is typically of short length.
|
static DateTimeFormatter |
ofLocalizedDateTime(FormatStyle dateStyle,
FormatStyle timeStyle)
Returns a locale specific date and time format.
|
static DateTimeFormatter |
ofLocalizedTime(FormatStyle timeStyle)
Returns a locale specific time format.
|
static DateTimeFormatter |
ofPattern(String pattern)
Creates a formatter using the specified pattern.
|
static DateTimeFormatter |
ofPattern(String pattern,
Locale locale)
Creates a formatter using the specified pattern.
|
TemporalAccessor |
parse(CharSequence text)
Fully parses the text producing a temporal object.
|
TemporalAccessor |
parse(CharSequence text,
ParsePosition position)
Parses the text using this formatter, providing control over the text position.
|
<T> T |
parse(CharSequence text,
TemporalQuery<T> query)
Fully parses the text producing an object of the specified type.
|
TemporalAccessor |
parseBest(CharSequence text,
TemporalQuery<?>... queries)
Fully parses the text producing an object of one of the specified types.
|
TemporalAccessor |
parseUnresolved(CharSequence text,
ParsePosition position)
Parses the text using this formatter, without resolving the result, intended
for advanced use cases.
|
Format |
toFormat()
Returns this formatter as a
java.text.Format instance. |
Format |
toFormat(TemporalQuery<?> parseQuery)
Returns this formatter as a
java.text.Format instance that will
parse using the specified query. |
String |
toString()
Returns a description of the underlying formatters.
|
DateTimeFormatter |
withChronology(Chronology chrono)
Returns a copy of this formatter with a new override chronology.
|
DateTimeFormatter |
withLocale(Locale locale)
Returns a copy of this formatter with a new locale.
|
DateTimeFormatter |
withSymbols(DateTimeFormatSymbols symbols)
Returns a copy of this formatter with a new set of symbols.
|
DateTimeFormatter |
withZone(ZoneId zone)
Returns a copy of this formatter with a new override zone.
|
public static final DateTimeFormatter ISO_LOCAL_DATE
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended local date format. The format consists of:
year
.
Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits.
Years outside that range will have a prefixed positive or negative symbol.
month-of-year
.
This is pre-padded by zero to ensure two digits.
day-of-month
.
This is pre-padded by zero to ensure two digits.
public static final DateTimeFormatter ISO_OFFSET_DATE
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended offset date format. The format consists of:
ISO_LOCAL_DATE
offset ID
. If the offset has seconds then
they will be handled even though this is not part of the ISO-8601 standard.
Parsing is case insensitive.
public static final DateTimeFormatter ISO_DATE
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended date format. The format consists of:
ISO_LOCAL_DATE
offset ID
. If the offset has seconds then
they will be handled even though this is not part of the ISO-8601 standard.
Parsing is case insensitive.
As this formatter has an optional element, it may be necessary to parse using
parseBest(java.lang.CharSequence, java.time.temporal.TemporalQuery<?>...)
.
public static final DateTimeFormatter ISO_LOCAL_TIME
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended local time format. The format consists of:
hour-of-day
.
This is pre-padded by zero to ensure two digits.
minute-of-hour
.
This is pre-padded by zero to ensure two digits.
second-of-minute
.
This is pre-padded by zero to ensure two digits.
nano-of-second
.
As many digits will be output as required.
public static final DateTimeFormatter ISO_OFFSET_TIME
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended offset time format. The format consists of:
ISO_LOCAL_TIME
offset ID
. If the offset has seconds then
they will be handled even though this is not part of the ISO-8601 standard.
Parsing is case insensitive.
public static final DateTimeFormatter ISO_TIME
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended offset time format. The format consists of:
ISO_LOCAL_TIME
offset ID
. If the offset has seconds then
they will be handled even though this is not part of the ISO-8601 standard.
Parsing is case insensitive.
As this formatter has an optional element, it may be necessary to parse using
parseBest(java.lang.CharSequence, java.time.temporal.TemporalQuery<?>...)
.
public static final DateTimeFormatter ISO_LOCAL_DATE_TIME
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended offset date-time format. The format consists of:
ISO_LOCAL_DATE
ISO_LOCAL_TIME
public static final DateTimeFormatter ISO_OFFSET_DATE_TIME
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended offset date-time format. The format consists of:
ISO_LOCAL_DATE_TIME
offset ID
. If the offset has seconds then
they will be handled even though this is not part of the ISO-8601 standard.
Parsing is case insensitive.
public static final DateTimeFormatter ISO_ZONED_DATE_TIME
This returns an immutable formatter capable of formatting and parsing a format that extends the ISO-8601 extended offset date-time format to add the time-zone. The format consists of:
ISO_OFFSET_DATE_TIME
ZoneOffset
then the format is complete.
zone ID
. This is not part of the ISO-8601 standard.
Parsing is case sensitive.
public static final DateTimeFormatter ISO_DATE_TIME
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended offset date-time format. The format consists of:
ISO_LOCAL_DATE_TIME
offset ID
. If the offset has seconds then
they will be handled even though this is not part of the ISO-8601 standard.
ZoneOffset
then the format is complete.
zone ID
. This is not part of the ISO-8601 standard.
Parsing is case sensitive.
As this formatter has an optional element, it may be necessary to parse using
parseBest(java.lang.CharSequence, java.time.temporal.TemporalQuery<?>...)
.
public static final DateTimeFormatter ISO_ORDINAL_DATE
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended ordinal date format. The format consists of:
year
.
Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits.
Years outside that range will have a prefixed positive or negative symbol.
day-of-year
.
This is pre-padded by zero to ensure three digits.
offset ID
. If the offset has seconds then
they will be handled even though this is not part of the ISO-8601 standard.
Parsing is case insensitive.
As this formatter has an optional element, it may be necessary to parse using
parseBest(java.lang.CharSequence, java.time.temporal.TemporalQuery<?>...)
.
public static final DateTimeFormatter ISO_WEEK_DATE
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended week-based date format. The format consists of:
week-based-year
.
Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits.
Years outside that range will have a prefixed positive or negative symbol.
week-of-week-based-year
.
This is pre-padded by zero to ensure three digits.
day-of-week
.
The value run from Monday (1) to Sunday (7).
offset ID
. If the offset has seconds then
they will be handled even though this is not part of the ISO-8601 standard.
Parsing is case insensitive.
As this formatter has an optional element, it may be necessary to parse using
parseBest(java.lang.CharSequence, java.time.temporal.TemporalQuery<?>...)
.
public static final DateTimeFormatter ISO_INSTANT
This returns an immutable formatter capable of formatting and parsing the ISO-8601 instant format. The format consists of:
ISO_OFFSET_DATE_TIME
where the instant is converted from
ChronoField.INSTANT_SECONDS
and ChronoField.NANO_OF_SECOND
using the UTC
offset. Parsing is case insensitive.
public static final DateTimeFormatter BASIC_ISO_DATE
This returns an immutable formatter capable of formatting and parsing the ISO-8601 basic local date format. The format consists of:
year
.
Only years in the range 0000 to 9999 are supported.
month-of-year
.
This is pre-padded by zero to ensure two digits.
day-of-month
.
This is pre-padded by zero to ensure two digits.
offset ID
without colons. If the offset has
seconds then they will be handled even though this is not part of the ISO-8601 standard.
Parsing is case insensitive.
As this formatter has an optional element, it may be necessary to parse using
parseBest(java.lang.CharSequence, java.time.temporal.TemporalQuery<?>...)
.
public static final DateTimeFormatter RFC_1123_DATE_TIME
This returns an immutable formatter capable of formatting and parsing most of the RFC-1123 format. RFC-1123 updates RFC-822 changing the year from two digits to four. This implementation requires a four digit year. This implementation also does not handle North American or military zone names, only 'GMT' and offset amounts.
The format consists of:
day-of-week
in English.
day-of-month
.
month-of-year
in English.
year
.
Only years in the range 0000 to 9999 are supported.
hour-of-day
.
This is pre-padded by zero to ensure two digits.
minute-of-hour
.
This is pre-padded by zero to ensure two digits.
second-of-minute
.
This is pre-padded by zero to ensure two digits.
offset ID
without colons or seconds.
An offset of zero uses "GMT". North American zone names and military zone names are not handled.
Parsing is case insensitive.
public static DateTimeFormatter ofPattern(String pattern)
This method will create a formatter based on a simple pattern of letters and symbols.
For example, d MMM yyyy
will format 2011-12-03 as '3 Dec 2011'.
The returned formatter will use the default locale, but this can be changed
using withLocale(Locale)
.
All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The following pattern letters are defined:
Symbol Meaning Presentation Examples ------ ------- ------------ ------- G era text A; AD; Anno Domini y year year 2004; 04 D day-of-year number 189 M month-of-year number/text 7; 07; Jul; July; J d day-of-month number 10 Q quarter-of-year number/text 3; 03; Q3 Y week-based-year year 1996; 96 w week-of-year number 27 W week-of-month number 27 e localized day-of-week number 2; Tue; Tuesday; T E day-of-week number/text 2; Tue; Tuesday; T F week-of-month number 3 a am-pm-of-day text PM h clock-hour-of-am-pm (1-12) number 12 K hour-of-am-pm (0-11) number 0 k clock-hour-of-am-pm (1-24) number 0 H hour-of-day (0-23) number 0 m minute-of-hour number 30 s second-of-minute number 55 S fraction-of-second fraction 978 A milli-of-day number 1234 n nano-of-second number 987654321 N nano-of-day number 1234000000 V time-zone ID zone-id America/Los_Angeles; Z; -08:30 z time-zone name zone-name Pacific Standard Time; PST X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15; x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15; Z zone-offset offset-Z +0000; -0800; -08:00; p pad next pad modifier 1 ' escape for text delimiter '' single quote literal ' [ optional section start ] optional section end {} reserved for future use
The count of pattern letters determine the format.
Text: The text style is determined based on the number of pattern letters used.
Less than 4 pattern letters will use the short form
.
Exactly 4 pattern letters will use the full form
.
Exactly 5 pattern letters will use the narrow form
.
Number: If the count of letters is one, then the value is output using the minimum number
of digits and without padding as per DateTimeFormatterBuilder.appendValue(java.time.temporal.TemporalField)
.
Otherwise, the count of digits is used as the width of the output field as per
DateTimeFormatterBuilder.appendValue(java.time.temporal.TemporalField, int)
.
Number/Text: If the count of pattern letters is 3 or greater, use the Text rules above. Otherwise use the Number rules above.
Fraction: Outputs the nano-of-second field as a fraction-of-second. The nano-of-second value has nine digits, thus the count of pattern letters is from 1 to 9. If it is less than 9, then the nano-of-second value is truncated, with only the most significant digits being output. When parsing in strict mode, the number of parsed digits must match the count of pattern letters. When parsing in lenient mode, the number of parsed digits must be at least the count of pattern letters, up to 9 digits.
Year: The count of letters determines the minimum field width below which padding is used.
If the count of letters is two, then a reduced
two digit form is used.
For printing, this outputs the rightmost two digits. For parsing, this will parse using the
base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.
If the count of letters is less than four (but not two), then the sign is only output for negative
years as per SignStyle.NORMAL
.
Otherwise, the sign is output if the pad width is exceeded, as per SignStyle.EXCEEDS_PAD
ZoneId: This outputs the time-zone ID, such as 'Europe/Paris'.
If the count of letters is two, then the time-zone ID is output.
Any other count of letters throws IllegalArgumentException
.
Zone names: This outputs the display name of the time-zone ID.
If the count of letters is one, two or three, then the short name is output.
If the count of letters is four, then the full name is output.
Five or more letters throws IllegalArgumentException
.
Offset X and x: This formats the offset based on the number of pattern letters.
One letter outputs just the hour', such as '+01', unless the minute is non-zero
in which case the minute is also output, such as '+0130'.
Two letters outputs the hour and minute, without a colon, such as '+0130'.
Three letters outputs the hour and minute, with a colon, such as '+01:30'.
Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'.
Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'.
Six or more letters throws IllegalArgumentException
.
Pattern letter 'X' (upper case) will output 'Z' when the offset to be output would be zero,
whereas pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'.
Offset Z: This formats the offset based on the number of pattern letters.
One, two or three letters outputs the hour and minute, without a colon, such as '+0130'.
Four or more letters throws IllegalArgumentException
.
The output will be '+0000' when the offset is zero.
Optional section: The optional section markers work exactly like calling
DateTimeFormatterBuilder.optionalStart()
and DateTimeFormatterBuilder.optionalEnd()
.
Pad modifier: Modifies the pattern that immediately follows to be padded with spaces.
The pad width is determined by the number of pattern letters.
This is the same as calling DateTimeFormatterBuilder.padNext(int)
.
For example, 'ppH' outputs the hour-of-day padded on the left with spaces to a width of 2.
Any unrecognized letter is an error. Any non-letter character, other than '[', ']', '{', '}' and the single quote will be output directly. Despite this, it is recommended to use single quotes around all characters that you want to output directly to ensure that future changes do not break your application.
pattern
- the pattern to use, not nullIllegalArgumentException
- if the pattern is invalidDateTimeFormatterBuilder.appendPattern(String)
public static DateTimeFormatter ofPattern(String pattern, Locale locale)
This method will create a formatter based on a simple pattern of letters and symbols.
For example, d MMM yyyy
will format 2011-12-03 as '3 Dec 2011'.
See ofPattern(String)
for details of the pattern.
The returned formatter will use the specified locale, but this can be changed
using withLocale(Locale)
.
pattern
- the pattern to use, not nulllocale
- the locale to use, not nullIllegalArgumentException
- if the pattern is invalidDateTimeFormatterBuilder.appendPattern(String)
public static DateTimeFormatter ofLocalizedDate(FormatStyle dateStyle)
This returns a formatter that will format or parse a date. The exact format pattern used varies by locale.
The locale is determined from the formatter. The formatter returned directly by
this method will use the default FORMAT locale
.
The locale can be controlled using withLocale(Locale)
on the result of this method.
Note that the localized pattern is looked up lazily.
This DateTimeFormatter
holds the style required and the locale,
looking up the pattern required on demand.
dateStyle
- the formatter style to obtain, not nullpublic static DateTimeFormatter ofLocalizedTime(FormatStyle timeStyle)
This returns a formatter that will format or parse a time. The exact format pattern used varies by locale.
The locale is determined from the formatter. The formatter returned directly by
this method will use the default FORMAT locale
.
The locale can be controlled using withLocale(Locale)
on the result of this method.
Note that the localized pattern is looked up lazily.
This DateTimeFormatter
holds the style required and the locale,
looking up the pattern required on demand.
timeStyle
- the formatter style to obtain, not nullpublic static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateTimeStyle)
This returns a formatter that will format or parse a date-time. The exact format pattern used varies by locale.
The locale is determined from the formatter. The formatter returned directly by
this method will use the default FORMAT locale
.
The locale can be controlled using withLocale(Locale)
on the result of this method.
Note that the localized pattern is looked up lazily.
This DateTimeFormatter
holds the style required and the locale,
looking up the pattern required on demand.
dateTimeStyle
- the formatter style to obtain, not nullpublic static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle)
This returns a formatter that will format or parse a date-time. The exact format pattern used varies by locale.
The locale is determined from the formatter. The formatter returned directly by
this method will use the default FORMAT locale
.
The locale can be controlled using withLocale(Locale)
on the result of this method.
Note that the localized pattern is looked up lazily.
This DateTimeFormatter
holds the style required and the locale,
looking up the pattern required on demand.
dateStyle
- the date formatter style to obtain, not nulltimeStyle
- the time formatter style to obtain, not nullpublic Locale getLocale()
This is used to lookup any part of the formatter needing specific localization, such as the text or localized pattern.
public DateTimeFormatter withLocale(Locale locale)
This is used to lookup any part of the formatter needing specific localization, such as the text or localized pattern.
This instance is immutable and unaffected by this method call.
locale
- the new locale, not nullpublic DateTimeFormatSymbols getSymbols()
public DateTimeFormatter withSymbols(DateTimeFormatSymbols symbols)
This instance is immutable and unaffected by this method call.
symbols
- the new symbols, not nullpublic Chronology getChronology()
This returns the override chronology, used to convert dates.
By default, a formatter has no override chronology, returning null.
See withChronology(Chronology)
for more details on overriding.
public DateTimeFormatter withChronology(Chronology chrono)
This returns a formatter with similar state to this formatter but with the override chronology set. By default, a formatter has no override chronology, returning null.
If an override is added, then any date that is formatted or parsed will be affected.
When formatting, if the Temporal
object contains a date then it will
be converted to a date in the override chronology.
Any time or zone will be retained unless overridden.
The converted result will behave in a manner equivalent to an implementation
of ChronoLocalDate
,ChronoLocalDateTime
or ChronoZonedDateTime
.
When parsing, the override chronology will be used to interpret the
fields
into a date unless the
formatter directly parses a valid chronology.
This instance is immutable and unaffected by this method call.
chrono
- the new chronology, not nullpublic ZoneId getZone()
This returns the override zone, used to convert instants.
By default, a formatter has no override zone, returning null.
See withZone(ZoneId)
for more details on overriding.
public DateTimeFormatter withZone(ZoneId zone)
This returns a formatter with similar state to this formatter but with the override zone set. By default, a formatter has no override zone, returning null.
If an override is added, then any instant that is formatted or parsed will be affected.
When formatting, if the Temporal
object contains an instant then it will
be converted to a zoned date-time using the override zone.
If the input has a chronology then it will be retained unless overridden.
If the input does not have a chronology, such as Instant
, then
the ISO chronology will be used.
The converted result will behave in a manner equivalent to an implementation
of ChronoZonedDateTime
.
When parsing, the override zone will be used to interpret the
fields
into an instant unless the
formatter directly parses a valid zone.
This instance is immutable and unaffected by this method call.
zone
- the new override zone, not nullpublic String format(TemporalAccessor temporal)
This formats the date-time to a String using the rules of the formatter.
temporal
- the temporal object to format, not nullDateTimeException
- if an error occurs during formattingpublic void formatTo(TemporalAccessor temporal, Appendable appendable)
Appendable
using this formatter.
This outputs the formatted date-time to the specified destination.
Appendable
is a general purpose interface that is implemented by all
key character output classes including StringBuffer
, StringBuilder
,
PrintStream
and Writer
.
Although Appendable
methods throw an IOException
, this method does not.
Instead, any IOException
is wrapped in a runtime exception.
temporal
- the temporal object to format, not nullappendable
- the appendable to format to, not nullDateTimeException
- if an error occurs during formattingpublic TemporalAccessor parse(CharSequence text)
This parses the entire text producing a temporal object.
It is typically more useful to use parse(CharSequence, TemporalQuery)
.
The result of this method is TemporalAccessor
which has been resolved,
applying basic validation checks to help ensure a valid date-time.
If the parse completes without reading the entire length of the text, or a problem occurs during parsing or merging, then an exception is thrown.
text
- the text to parse, not nullDateTimeParseException
- if unable to parse the requested resultpublic TemporalAccessor parse(CharSequence text, ParsePosition position)
This parses the text without requiring the parse to start from the beginning
of the string or finish at the end.
The result of this method is TemporalAccessor
which has been resolved,
applying basic validation checks to help ensure a valid date-time.
The text will be parsed from the specified start ParsePosition
.
The entire length of the text does not have to be parsed, the ParsePosition
will be updated with the index at the end of parsing.
The operation of this method is slightly different to similar methods using
ParsePosition
on java.text.Format
. That class will return
errors using the error index on the ParsePosition
. By contrast, this
method will throw a DateTimeParseException
if an error occurs, with
the exception containing the error index.
This change in behavior is necessary due to the increased complexity of
parsing and resolving dates/times in this API.
If the formatter parses the same field more than once with different values, the result will be an error.
text
- the text to parse, not nullposition
- the position to parse from, updated with length parsed
and the index of any error, not nullDateTimeParseException
- if unable to parse the requested resultIndexOutOfBoundsException
- if the position is invalidpublic <T> T parse(CharSequence text, TemporalQuery<T> query)
Most applications should use this method for parsing.
It parses the entire text to produce the required date-time.
The query is typically a method reference to a from(TemporalAccessor)
method.
For example:
LocalDateTime dt = parser.parse(str, LocalDateTime::from);If the parse completes without reading the entire length of the text, or a problem occurs during parsing or merging, then an exception is thrown.
T
- the type of the parsed date-timetext
- the text to parse, not nullquery
- the query defining the type to parse to, not nullDateTimeParseException
- if unable to parse the requested resultpublic TemporalAccessor parseBest(CharSequence text, TemporalQuery<?>... queries)
This parse method is convenient for use when the parser can handle optional elements.
For example, a pattern of 'yyyy-MM-dd HH.mm[Z]]' can be fully parsed to a ZonedDateTime
,
or partially parsed to a LocalDateTime
.
The queries must be specified in order, starting from the best matching full-parse option
and ending with the worst matching minimal parse option.
The query is typically a method reference to a from(TemporalAccessor)
method.
The result is associated with the first type that successfully parses.
Normally, applications will use instanceof
to check the result.
For example:
TemporalAccessor dt = parser.parseBest(str, ZonedDateTime::from, LocalDateTime::from); if (dt instanceof ZonedDateTime) { ... } else { ... }If the parse completes without reading the entire length of the text, or a problem occurs during parsing or merging, then an exception is thrown.
text
- the text to parse, not nullqueries
- the queries defining the types to attempt to parse to,
must implement TemporalAccessor
, not nullIllegalArgumentException
- if less than 2 types are specifiedDateTimeParseException
- if unable to parse the requested resultpublic TemporalAccessor parseUnresolved(CharSequence text, ParsePosition position)
Parsing is implemented as a two-phase operation.
First, the text is parsed using the layout defined by the formatter, producing
a Map
of field to value, a ZoneId
and a Chronology
.
Second, the parsed data is resolved, by validating, combining and
simplifying the various fields into more useful ones.
This method performs the parsing stage but not the resolving stage.
The result of this method is TemporalAccessor
which represents the
data as seen in the input. Values are not validated, thus parsing a date string
of '2012-00-65' would result in a temporal with three fields - year of '2012',
month of '0' and day-of-month of '65'.
The text will be parsed from the specified start ParsePosition
.
The entire length of the text does not have to be parsed, the ParsePosition
will be updated with the index at the end of parsing.
Errors are returned using the error index field of the ParsePosition
instead of DateTimeParseException
.
The returned error index will be set to an index indicative of the error.
Callers must check for errors before using the context.
If the formatter parses the same field more than once with different values, the result will be an error.
This method is intended for advanced use cases that need access to the
internal state during parsing. Typical application code should use
parse(CharSequence, TemporalQuery)
or the parse method on the target type.
text
- the text to parse, not nullposition
- the position to parse from, updated with length parsed
and the index of any error, not nullDateTimeException
- if some problem occurs during parsingIndexOutOfBoundsException
- if the position is invalidpublic Format toFormat()
java.text.Format
instance.
The returned Format
instance will format any TemporalAccessor
and parses to a resolved TemporalAccessor
.
Exceptions will follow the definitions of Format
, see those methods
for details about IllegalArgumentException
during formatting and
ParseException
or null during parsing.
The format does not support attributing of the returned format string.
public Format toFormat(TemporalQuery<?> parseQuery)
java.text.Format
instance that will
parse using the specified query.
The returned Format
instance will format any TemporalAccessor
and parses to the type specified.
The type must be one that is supported by parse(java.lang.CharSequence)
.
Exceptions will follow the definitions of Format
, see those methods
for details about IllegalArgumentException
during formatting and
ParseException
or null during parsing.
The format does not support attributing of the returned format string.
parseQuery
- the query defining the type to parse to, not null Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2013, Oracle and/or its affiliates. All rights reserved.
DRAFT internal-0