1 /*
2  * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 /*
27  * This file is available under and governed by the GNU General Public
28  * License version 2 only, as published by the Free Software Foundation.
29  * However, the following notice accompanied the original version of this
30  * file:
31  *
32  * Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos
33  *
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions are met:
38  *
39  *  * Redistributions of source code must retain the above copyright notice,
40  *    this list of conditions and the following disclaimer.
41  *
42  *  * Redistributions in binary form must reproduce the above copyright notice,
43  *    this list of conditions and the following disclaimer in the documentation
44  *    and/or other materials provided with the distribution.
45  *
46  *  * Neither the name of JSR-310 nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61  */
62 package java.time.format;
63 
64 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
65 import static java.time.temporal.ChronoField.DAY_OF_WEEK;
66 import static java.time.temporal.ChronoField.DAY_OF_YEAR;
67 import static java.time.temporal.ChronoField.HOUR_OF_DAY;
68 import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
69 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
70 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
71 import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
72 import static java.time.temporal.ChronoField.YEAR;
73 
74 import java.io.IOException;
75 import java.text.FieldPosition;
76 import java.text.Format;
77 import java.text.ParseException;
78 import java.text.ParsePosition;
79 import java.time.DateTimeException;
80 import java.time.Period;
81 import java.time.ZoneId;
82 import java.time.ZoneOffset;
83 import java.time.chrono.ChronoLocalDateTime;
84 import java.time.chrono.Chronology;
85 import java.time.chrono.IsoChronology;
86 import java.time.format.DateTimeFormatterBuilder.CompositePrinterParser;
87 import java.time.temporal.ChronoField;
88 import java.time.temporal.IsoFields;
89 import java.time.temporal.TemporalAccessor;
90 import java.time.temporal.TemporalField;
91 import java.time.temporal.TemporalQuery;
92 import java.util.Arrays;
93 import java.util.Collections;
94 import java.util.HashMap;
95 import java.util.HashSet;
96 import java.util.Locale;
97 import java.util.Map;
98 import java.util.Objects;
99 import java.util.Optional;
100 import java.util.Set;
101 import libcore.icu.ICU;
102 
103 // Android-changed: Remove period-of-day from javadoc temporarily.
104 /**
105  * Formatter for printing and parsing date-time objects.
106  * <p>
107  * This class provides the main application entry point for printing and parsing
108  * and provides common implementations of {@code DateTimeFormatter}:
109  * <ul>
110  * <li>Using predefined constants, such as {@link #ISO_LOCAL_DATE}</li>
111  * <li>Using pattern letters, such as {@code uuuu-MMM-dd}</li>
112  * <li>Using localized styles, such as {@code long} or {@code medium}</li>
113  * </ul>
114  * <p>
115  * More complex formatters are provided by
116  * {@link DateTimeFormatterBuilder DateTimeFormatterBuilder}.
117  *
118  * <p>
119  * The main date-time classes provide two methods - one for formatting,
120  * {@code format(DateTimeFormatter formatter)}, and one for parsing,
121  * {@code parse(CharSequence text, DateTimeFormatter formatter)}.
122  * <p>For example:
123  * <blockquote><pre>
124  *  LocalDate date = LocalDate.now();
125  *  String text = date.format(formatter);
126  *  LocalDate parsedDate = LocalDate.parse(text, formatter);
127  * </pre></blockquote>
128  * <p>
129  * In addition to the format, formatters can be created with desired Locale,
130  * Chronology, ZoneId, and DecimalStyle.
131  * <p>
132  * The {@link #withLocale withLocale} method returns a new formatter that
133  * overrides the locale. The locale affects some aspects of formatting and
134  * parsing. For example, the {@link #ofLocalizedDate ofLocalizedDate} provides a
135  * formatter that uses the locale specific date format.
136  * <p>
137  * The {@link #withChronology withChronology} method returns a new formatter
138  * that overrides the chronology. If overridden, the date-time value is
139  * converted to the chronology before formatting. During parsing the date-time
140  * value is converted to the chronology before it is returned.
141  * <p>
142  * The {@link #withZone withZone} method returns a new formatter that overrides
143  * the zone. If overridden, the date-time value is converted to a ZonedDateTime
144  * with the requested ZoneId before formatting. During parsing the ZoneId is
145  * applied before the value is returned.
146  * <p>
147  * The {@link #withDecimalStyle withDecimalStyle} method returns a new formatter that
148  * overrides the {@link DecimalStyle}. The DecimalStyle symbols are used for
149  * formatting and parsing.
150  * <p>
151  * Some applications may need to use the older {@link Format java.text.Format}
152  * class for formatting. The {@link #toFormat()} method returns an
153  * implementation of {@code java.text.Format}.
154  *
155  * <h2 id="predefined">Predefined Formatters</h2>
156  * <table class="striped" style="text-align:left">
157  * <caption>Predefined Formatters</caption>
158  * <thead>
159  * <tr>
160  * <th scope="col">Formatter</th>
161  * <th scope="col">Description</th>
162  * <th scope="col">Example</th>
163  * </tr>
164  * </thead>
165  * <tbody>
166  * <tr>
167  * <th scope="row">{@link #ofLocalizedDate ofLocalizedDate(dateStyle)} </th>
168  * <td> Formatter with date style from the locale </td>
169  * <td> '2011-12-03'</td>
170  * </tr>
171  * <tr>
172  * <th scope="row"> {@link #ofLocalizedTime ofLocalizedTime(timeStyle)} </th>
173  * <td> Formatter with time style from the locale </td>
174  * <td> '10:15:30'</td>
175  * </tr>
176  * <tr>
177  * <th scope="row"> {@link #ofLocalizedDateTime ofLocalizedDateTime(dateTimeStyle)} </th>
178  * <td> Formatter with a style for date and time from the locale</td>
179  * <td> '3 Jun 2008 11:05:30'</td>
180  * </tr>
181  * <tr>
182  * <th scope="row"> {@link #ofLocalizedDateTime ofLocalizedDateTime(dateStyle,timeStyle)}
183  * </th>
184  * <td> Formatter with date and time styles from the locale </td>
185  * <td> '3 Jun 2008 11:05'</td>
186  * </tr>
187  * <tr>
188  * <th scope="row"> {@link #BASIC_ISO_DATE}</th>
189  * <td>Basic ISO date </td> <td>'20111203'</td>
190  * </tr>
191  * <tr>
192  * <th scope="row"> {@link #ISO_LOCAL_DATE}</th>
193  * <td> ISO Local Date </td>
194  * <td>'2011-12-03'</td>
195  * </tr>
196  * <tr>
197  * <th scope="row"> {@link #ISO_OFFSET_DATE}</th>
198  * <td> ISO Date with offset </td>
199  * <td>'2011-12-03+01:00'</td>
200  * </tr>
201  * <tr>
202  * <th scope="row"> {@link #ISO_DATE}</th>
203  * <td> ISO Date with or without offset </td>
204  * <td> '2011-12-03+01:00'; '2011-12-03'</td>
205  * </tr>
206  * <tr>
207  * <th scope="row"> {@link #ISO_LOCAL_TIME}</th>
208  * <td> Time without offset </td>
209  * <td>'10:15:30'</td>
210  * </tr>
211  * <tr>
212  * <th scope="row"> {@link #ISO_OFFSET_TIME}</th>
213  * <td> Time with offset </td>
214  * <td>'10:15:30+01:00'</td>
215  * </tr>
216  * <tr>
217  * <th scope="row"> {@link #ISO_TIME}</th>
218  * <td> Time with or without offset </td>
219  * <td>'10:15:30+01:00'; '10:15:30'</td>
220  * </tr>
221  * <tr>
222  * <th scope="row"> {@link #ISO_LOCAL_DATE_TIME}</th>
223  * <td> ISO Local Date and Time </td>
224  * <td>'2011-12-03T10:15:30'</td>
225  * </tr>
226  * <tr>
227  * <th scope="row"> {@link #ISO_OFFSET_DATE_TIME}</th>
228  * <td> Date Time with Offset
229  * </td><td>'2011-12-03T10:15:30+01:00'</td>
230  * </tr>
231  * <tr>
232  * <th scope="row"> {@link #ISO_ZONED_DATE_TIME}</th>
233  * <td> Zoned Date Time </td>
234  * <td>'2011-12-03T10:15:30+01:00[Europe/Paris]'</td>
235  * </tr>
236  * <tr>
237  * <th scope="row"> {@link #ISO_DATE_TIME}</th>
238  * <td> Date and time with ZoneId </td>
239  * <td>'2011-12-03T10:15:30+01:00[Europe/Paris]'</td>
240  * </tr>
241  * <tr>
242  * <th scope="row"> {@link #ISO_ORDINAL_DATE}</th>
243  * <td> Year and day of year </td>
244  * <td>'2012-337'</td>
245  * </tr>
246  * <tr>
247  * <th scope="row"> {@link #ISO_WEEK_DATE}</th>
248  * <td> Year and Week </td>
249  * <td>'2012-W48-6'</td></tr>
250  * <tr>
251  * <th scope="row"> {@link #ISO_INSTANT}</th>
252  * <td> Date and Time of an Instant </td>
253  * <td>'2011-12-03T10:15:30Z' </td>
254  * </tr>
255  * <tr>
256  * <th scope="row"> {@link #RFC_1123_DATE_TIME}</th>
257  * <td> RFC 1123 / RFC 822 </td>
258  * <td>'Tue, 3 Jun 2008 11:05:30 GMT'</td>
259  * </tr>
260  * </tbody>
261  * </table>
262  *
263  * <h2 id="patterns">Patterns for Formatting and Parsing</h2>
264  * Patterns are based on a simple sequence of letters and symbols.
265  * A pattern is used to create a Formatter using the
266  * {@link #ofPattern(String)} and {@link #ofPattern(String, Locale)} methods.
267  * For example,
268  * {@code "d MMM uuuu"} will format 2011-12-03 as '3&nbsp;Dec&nbsp;2011'.
269  * A formatter created from a pattern can be used as many times as necessary,
270  * it is immutable and is thread-safe.
271  * <p>
272  * For example:
273  * <blockquote><pre>
274  *  LocalDate date = LocalDate.now();
275  *  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
276  *  String text = date.format(formatter);
277  *  LocalDate parsedDate = LocalDate.parse(text, formatter);
278  * </pre></blockquote>
279  * <p>
280  * All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The
281  * following pattern letters are defined:
282  * <table class="striped">
283  * <caption>Pattern Letters and Symbols</caption>
284  * <thead>
285  *  <tr><th scope="col">Symbol</th>   <th scope="col">Meaning</th>         <th scope="col">Presentation</th> <th scope="col">Examples</th>
286  * </thead>
287  * <tbody>
288  *   <tr><th scope="row">G</th>       <td>era</td>                         <td>text</td>              <td>AD; Anno Domini; A</td>
289  *   <tr><th scope="row">u</th>       <td>year</td>                        <td>year</td>              <td>2004; 04</td>
290  *   <tr><th scope="row">y</th>       <td>year-of-era</td>                 <td>year</td>              <td>2004; 04</td>
291  *   <tr><th scope="row">D</th>       <td>day-of-year</td>                 <td>number</td>            <td>189</td>
292  *   <tr><th scope="row">M/L</th>     <td>month-of-year</td>               <td>number/text</td>       <td>7; 07; Jul; July; J</td>
293  *   <tr><th scope="row">d</th>       <td>day-of-month</td>                <td>number</td>            <td>10</td>
294  *   <tr><th scope="row">g</th>       <td>modified-julian-day</td>         <td>number</td>            <td>2451334</td>
295  *
296  *   <tr><th scope="row">Q/q</th>     <td>quarter-of-year</td>             <td>number/text</td>       <td>3; 03; Q3; 3rd quarter</td>
297  *   <tr><th scope="row">Y</th>       <td>week-based-year</td>             <td>year</td>              <td>1996; 96</td>
298  *   <tr><th scope="row">w</th>       <td>week-of-week-based-year</td>     <td>number</td>            <td>27</td>
299  *   <tr><th scope="row">W</th>       <td>week-of-month</td>               <td>number</td>            <td>4</td>
300  *   <tr><th scope="row">E</th>       <td>day-of-week</td>                 <td>text</td>              <td>Tue; Tuesday; T</td>
301  *   <tr><th scope="row">e/c</th>     <td>localized day-of-week</td>       <td>number/text</td>       <td>2; 02; Tue; Tuesday; T</td>
302  *   <tr><th scope="row">F</th>       <td>day-of-week-in-month</td>        <td>number</td>            <td>3</td>
303  *
304  *   <tr><th scope="row">a</th>       <td>am-pm-of-day</td>                <td>text</td>              <td>PM</td>
305  *   <tr><th scope="row">h</th>       <td>clock-hour-of-am-pm (1-12)</td>  <td>number</td>            <td>12</td>
306  *   <tr><th scope="row">K</th>       <td>hour-of-am-pm (0-11)</td>        <td>number</td>            <td>0</td>
307  *   <tr><th scope="row">k</th>       <td>clock-hour-of-day (1-24)</td>    <td>number</td>            <td>24</td>
308  *
309  *   <tr><th scope="row">H</th>       <td>hour-of-day (0-23)</td>          <td>number</td>            <td>0</td>
310  *   <tr><th scope="row">m</th>       <td>minute-of-hour</td>              <td>number</td>            <td>30</td>
311  *   <tr><th scope="row">s</th>       <td>second-of-minute</td>            <td>number</td>            <td>55</td>
312  *   <tr><th scope="row">S</th>       <td>fraction-of-second</td>          <td>fraction</td>          <td>978</td>
313  *   <tr><th scope="row">A</th>       <td>milli-of-day</td>                <td>number</td>            <td>1234</td>
314  *   <tr><th scope="row">n</th>       <td>nano-of-second</td>              <td>number</td>            <td>987654321</td>
315  *   <tr><th scope="row">N</th>       <td>nano-of-day</td>                 <td>number</td>            <td>1234000000</td>
316  *
317  *   <tr><th scope="row">V</th>       <td>time-zone ID</td>                <td>zone-id</td>           <td>America/Los_Angeles; Z; -08:30</td>
318  *   <tr><th scope="row">v</th>       <td>generic time-zone name</td>      <td>zone-name</td>         <td>Pacific Time; PT</td>
319  *   <tr><th scope="row">z</th>       <td>time-zone name</td>              <td>zone-name</td>         <td>Pacific Standard Time; PST</td>
320  *   <tr><th scope="row">O</th>       <td>localized zone-offset</td>       <td>offset-O</td>          <td>GMT+8; GMT+08:00; UTC-08:00</td>
321  *   <tr><th scope="row">X</th>       <td>zone-offset 'Z' for zero</td>    <td>offset-X</td>          <td>Z; -08; -0830; -08:30; -083015; -08:30:15</td>
322  *   <tr><th scope="row">x</th>       <td>zone-offset</td>                 <td>offset-x</td>          <td>+0000; -08; -0830; -08:30; -083015; -08:30:15</td>
323  *   <tr><th scope="row">Z</th>       <td>zone-offset</td>                 <td>offset-Z</td>          <td>+0000; -0800; -08:00</td>
324  *
325  *   <tr><th scope="row">p</th>       <td>pad next</td>                    <td>pad modifier</td>      <td>1</td>
326  *
327  *   <tr><th scope="row">'</th>       <td>escape for text</td>             <td>delimiter</td>         <td></td>
328  *   <tr><th scope="row">''</th>      <td>single quote</td>                <td>literal</td>           <td>'</td>
329  *   <tr><th scope="row">[</th>       <td>optional section start</td>      <td></td>                  <td></td>
330  *   <tr><th scope="row">]</th>       <td>optional section end</td>        <td></td>                  <td></td>
331  *   <tr><th scope="row">#</th>       <td>reserved for future use</td>     <td></td>                  <td></td>
332  *   <tr><th scope="row">{</th>       <td>reserved for future use</td>     <td></td>                  <td></td>
333  *   <tr><th scope="row">}</th>       <td>reserved for future use</td>     <td></td>                  <td></td>
334  * </tbody>
335  * </table>
336  * <p>
337  * The count of pattern letters determines the format.
338  * <p>
339  * <b>Text</b>: The text style is determined based on the number of pattern
340  * letters used. Less than 4 pattern letters will use the
341  * {@link TextStyle#SHORT short form}. Exactly 4 pattern letters will use the
342  * {@link TextStyle#FULL full form}. Exactly 5 pattern letters will use the
343  * {@link TextStyle#NARROW narrow form}.
344  * Pattern letters 'L', 'c', and 'q' specify the stand-alone form of the text styles.
345  * <p>
346  * <b>Number</b>: If the count of letters is one, then the value is output using
347  * the minimum number of digits and without padding. Otherwise, the count of digits
348  * is used as the width of the output field, with the value zero-padded as necessary.
349  * The following pattern letters have constraints on the count of letters.
350  * Only one letter of 'c' and 'F' can be specified.
351  * Up to two letters of 'd', 'H', 'h', 'K', 'k', 'm', and 's' can be specified.
352  * Up to three letters of 'D' can be specified.
353  * <p>
354  * <b>Number/Text</b>: If the count of pattern letters is 3 or greater, use the
355  * Text rules above. Otherwise use the Number rules above.
356  * <p>
357  * <b>Fraction</b>: Outputs the nano-of-second field as a fraction-of-second.
358  * The nano-of-second value has nine digits, thus the count of pattern letters
359  * is from 1 to 9. If it is less than 9, then the nano-of-second value is
360  * truncated, with only the most significant digits being output.
361  * <p>
362  * <b>Year</b>: The count of letters determines the minimum field width below
363  * which padding is used. If the count of letters is two, then a
364  * {@link DateTimeFormatterBuilder#appendValueReduced reduced} two digit form is
365  * used. For printing, this outputs the rightmost two digits. For parsing, this
366  * will parse using the base value of 2000, resulting in a year within the range
367  * 2000 to 2099 inclusive. If the count of letters is less than four (but not
368  * two), then the sign is only output for negative years as per
369  * {@link SignStyle#NORMAL}. Otherwise, the sign is output if the pad width is
370  * exceeded, as per {@link SignStyle#EXCEEDS_PAD}.
371  * <p>
372  * <b>ZoneId</b>: This outputs the time-zone ID, such as 'Europe/Paris'. If the
373  * count of letters is two, then the time-zone ID is output. Any other count of
374  * letters throws {@code IllegalArgumentException}.
375  * <p>
376  * <b>Zone names</b>: This outputs the display name of the time-zone ID. If the
377  * pattern letter is 'z' the output is the daylight savings aware zone name.
378  * If there is insufficient information to determine whether DST applies,
379  * the name ignoring daylight savings time will be used.
380  * If the count of letters is one, two or three, then the short name is output.
381  * If the count of letters is four, then the full name is output.
382  * Five or more letters throws {@code IllegalArgumentException}.
383  * <p>
384  * If the pattern letter is 'v' the output provides the zone name ignoring
385  * daylight savings time. If the count of letters is one, then the short name is output.
386  * If the count of letters is four, then the full name is output.
387  * Two, three and five or more letters throw {@code IllegalArgumentException}.
388  * <p>
389  * <b>Offset X and x</b>: This formats the offset based on the number of pattern
390  * letters. One letter outputs just the hour, such as '+01', unless the minute
391  * is non-zero in which case the minute is also output, such as '+0130'. Two
392  * letters outputs the hour and minute, without a colon, such as '+0130'. Three
393  * letters outputs the hour and minute, with a colon, such as '+01:30'. Four
394  * letters outputs the hour and minute and optional second, without a colon,
395  * such as '+013015'. Five letters outputs the hour and minute and optional
396  * second, with a colon, such as '+01:30:15'. Six or more letters throws
397  * {@code IllegalArgumentException}. Pattern letter 'X' (upper case) will output
398  * 'Z' when the offset to be output would be zero, whereas pattern letter 'x'
399  * (lower case) will output '+00', '+0000', or '+00:00'.
400  * <p>
401  * <b>Offset O</b>: With a non-zero offset, this formats the localized offset
402  * based on the number of pattern letters. One letter outputs the
403  * {@linkplain TextStyle#SHORT short} form of the localized offset, which is
404  * localized offset text, such as 'GMT', with hour without leading zero, optional
405  * 2-digit minute and second if non-zero, and colon, for example 'GMT+8'. Four
406  * letters outputs the {@linkplain TextStyle#FULL full} form, which is localized
407  * offset text, such as 'GMT, with 2-digit hour and minute field, optional second
408  * field if non-zero, and colon, for example 'GMT+08:00'. If the offset is zero,
409  * only localized text is output. Any other count of letters throws
410  * {@code IllegalArgumentException}.
411  * <p>
412  * <b>Offset Z</b>: This formats the offset based on the number of pattern
413  * letters. One, two or three letters outputs the hour and minute, without a
414  * colon, such as '+0130'. The output will be '+0000' when the offset is zero.
415  * Four letters outputs the {@linkplain TextStyle#FULL full} form of localized
416  * offset, equivalent to four letters of Offset-O. The output will be the
417  * corresponding localized offset text if the offset is zero. Five
418  * letters outputs the hour, minute, with optional second if non-zero, with
419  * colon. It outputs 'Z' if the offset is zero.
420  * Six or more letters throws {@code IllegalArgumentException}.
421  * <p>
422  * <b>Optional section</b>: The optional section markers work exactly like
423  * calling {@link DateTimeFormatterBuilder#optionalStart()} and
424  * {@link DateTimeFormatterBuilder#optionalEnd()}.
425  * <p>
426  * <b>Pad modifier</b>: Modifies the pattern that immediately follows to be
427  * padded with spaces. The pad width is determined by the number of pattern
428  * letters. This is the same as calling
429  * {@link DateTimeFormatterBuilder#padNext(int)}.
430  * <p>
431  * For example, 'ppH' outputs the hour-of-day padded on the left with spaces to
432  * a width of 2.
433  * <p>
434  * Any unrecognized letter is an error. Any non-letter character, other than
435  * '[', ']', '{', '}', '#' and the single quote will be output directly.
436  * Despite this, it is recommended to use single quotes around all characters
437  * that you want to output directly to ensure that future changes do not break
438  * your application.
439  *
440  * <h2 id="resolving">Resolving</h2>
441  * Parsing is implemented as a two-phase operation.
442  * First, the text is parsed using the layout defined by the formatter, producing
443  * a {@code Map} of field to value, a {@code ZoneId} and a {@code Chronology}.
444  * Second, the parsed data is <em>resolved</em>, by validating, combining and
445  * simplifying the various fields into more useful ones.
446  * <p>
447  * Five parsing methods are supplied by this class.
448  * Four of these perform both the parse and resolve phases.
449  * The fifth method, {@link #parseUnresolved(CharSequence, ParsePosition)},
450  * only performs the first phase, leaving the result unresolved.
451  * As such, it is essentially a low-level operation.
452  * <p>
453  * The resolve phase is controlled by two parameters, set on this class.
454  * <p>
455  * The {@link ResolverStyle} is an enum that offers three different approaches,
456  * strict, smart and lenient. The smart option is the default.
457  * It can be set using {@link #withResolverStyle(ResolverStyle)}.
458  * <p>
459  * The {@link #withResolverFields(TemporalField...)} parameter allows the
460  * set of fields that will be resolved to be filtered before resolving starts.
461  * For example, if the formatter has parsed a year, month, day-of-month
462  * and day-of-year, then there are two approaches to resolve a date:
463  * (year + month + day-of-month) and (year + day-of-year).
464  * The resolver fields allows one of the two approaches to be selected.
465  * If no resolver fields are set then both approaches must result in the same date.
466  * <p>
467  * Resolving separate fields to form a complete date and time is a complex
468  * process with behaviour distributed across a number of classes.
469  * It follows these steps:
470  * <ol>
471  * <li>The chronology is determined.
472  * The chronology of the result is either the chronology that was parsed,
473  * or if no chronology was parsed, it is the chronology set on this class,
474  * or if that is null, it is {@code IsoChronology}.
475  * <li>The {@code ChronoField} date fields are resolved.
476  * This is achieved using {@link Chronology#resolveDate(Map, ResolverStyle)}.
477  * Documentation about field resolution is located in the implementation
478  * of {@code Chronology}.
479  * <li>The {@code ChronoField} time fields are resolved.
480  * This is documented on {@link ChronoField} and is the same for all chronologies.
481  * <li>Any fields that are not {@code ChronoField} are processed.
482  * This is achieved using {@link TemporalField#resolve(Map, TemporalAccessor, ResolverStyle)}.
483  * Documentation about field resolution is located in the implementation
484  * of {@code TemporalField}.
485  * <li>The {@code ChronoField} date and time fields are re-resolved.
486  * This allows fields in step four to produce {@code ChronoField} values
487  * and have them be processed into dates and times.
488  * <li>A {@code LocalTime} is formed if there is at least an hour-of-day available.
489  * This involves providing default values for minute, second and fraction of second.
490  * <li>Any remaining unresolved fields are cross-checked against any
491  * date and/or time that was resolved. Thus, an earlier stage would resolve
492  * (year + month + day-of-month) to a date, and this stage would check that
493  * day-of-week was valid for the date.
494  * <li>If an {@linkplain #parsedExcessDays() excess number of days}
495  * was parsed then it is added to the date if a date is available.
496  * <li> If a second-based field is present, but {@code LocalTime} was not parsed,
497  * then the resolver ensures that milli, micro and nano second values are
498  * available to meet the contract of {@link ChronoField}.
499  * These will be set to zero if missing.
500  * <li>If both date and time were parsed and either an offset or zone is present,
501  * the field {@link ChronoField#INSTANT_SECONDS} is created.
502  * If an offset was parsed then the offset will be combined with the
503  * {@code LocalDateTime} to form the instant, with any zone ignored.
504  * If a {@code ZoneId} was parsed without an offset then the zone will be
505  * combined with the {@code LocalDateTime} to form the instant using the rules
506  * of {@link ChronoLocalDateTime#atZone(ZoneId)}.
507  * </ol>
508  *
509  * @implSpec
510  * This class is immutable and thread-safe.
511  *
512  * @since 1.8
513  */
514 public final class DateTimeFormatter {
515 
516     /**
517      * The printer and/or parser to use, not null.
518      */
519     private final CompositePrinterParser printerParser;
520     /**
521      * The locale to use for formatting, not null.
522      */
523     private final Locale locale;
524     /**
525      * The symbols to use for formatting, not null.
526      */
527     private final DecimalStyle decimalStyle;
528     /**
529      * The resolver style to use, not null.
530      */
531     private final ResolverStyle resolverStyle;
532     /**
533      * The fields to use in resolving, null for all fields.
534      */
535     private final Set<TemporalField> resolverFields;
536     /**
537      * The chronology to use for formatting, null for no override.
538      */
539     private final Chronology chrono;
540     /**
541      * The zone to use for formatting, null for no override.
542      */
543     private final ZoneId zone;
544 
545     //-----------------------------------------------------------------------
546     /**
547      * Creates a formatter using the specified pattern.
548      * <p>
549      * This method will create a formatter based on a simple
550      * <a href="#patterns">pattern of letters and symbols</a>
551      * as described in the class documentation.
552      * For example, {@code d MMM uuuu} will format 2011-12-03 as '3 Dec 2011'.
553      * <p>
554      * The formatter will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}.
555      * This can be changed using {@link DateTimeFormatter#withLocale(Locale)} on the returned formatter.
556      * Alternatively use the {@link #ofPattern(String, Locale)} variant of this method.
557      * <p>
558      * The returned formatter has no override chronology or zone.
559      * It uses {@link ResolverStyle#SMART SMART} resolver style.
560      *
561      * @param pattern  the pattern to use, not null
562      * @return the formatter based on the pattern, not null
563      * @throws IllegalArgumentException if the pattern is invalid
564      * @see DateTimeFormatterBuilder#appendPattern(String)
565      */
ofPattern(String pattern)566     public static DateTimeFormatter ofPattern(String pattern) {
567         return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter();
568     }
569 
570     /**
571      * Creates a formatter using the specified pattern and locale.
572      * <p>
573      * This method will create a formatter based on a simple
574      * <a href="#patterns">pattern of letters and symbols</a>
575      * as described in the class documentation.
576      * For example, {@code d MMM uuuu} will format 2011-12-03 as '3 Dec 2011'.
577      * <p>
578      * The formatter will use the specified locale.
579      * This can be changed using {@link DateTimeFormatter#withLocale(Locale)} on the returned formatter.
580      * <p>
581      * The returned formatter has no override chronology or zone.
582      * It uses {@link ResolverStyle#SMART SMART} resolver style.
583      *
584      * @param pattern  the pattern to use, not null
585      * @param locale  the locale to use, not null
586      * @return the formatter based on the pattern, not null
587      * @throws IllegalArgumentException if the pattern is invalid
588      * @see DateTimeFormatterBuilder#appendPattern(String)
589      */
ofPattern(String pattern, Locale locale)590     public static DateTimeFormatter ofPattern(String pattern, Locale locale) {
591         return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(locale);
592     }
593 
594     //-----------------------------------------------------------------------
595     /**
596      * Returns a locale specific date format for the ISO chronology.
597      * <p>
598      * This returns a formatter that will format or parse a date.
599      * The exact format pattern used varies by locale.
600      * <p>
601      * The locale is determined from the formatter. The formatter returned directly by
602      * this method will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}.
603      * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
604      * on the result of this method.
605      * <p>
606      * Note that the localized pattern is looked up lazily.
607      * This {@code DateTimeFormatter} holds the style required and the locale,
608      * looking up the pattern required on demand.
609      * <p>
610      * The returned formatter has a chronology of ISO set to ensure dates in
611      * other calendar systems are correctly converted.
612      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
613      *
614      * @param dateStyle  the formatter style to obtain, not null
615      * @return the date formatter, not null
616      */
ofLocalizedDate(FormatStyle dateStyle)617     public static DateTimeFormatter ofLocalizedDate(FormatStyle dateStyle) {
618         Objects.requireNonNull(dateStyle, "dateStyle");
619         return new DateTimeFormatterBuilder().appendLocalized(dateStyle, null)
620                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
621     }
622 
623     /**
624      * Returns a locale specific time format for the ISO chronology.
625      * <p>
626      * This returns a formatter that will format or parse a time.
627      * The exact format pattern used varies by locale.
628      * <p>
629      * The locale is determined from the formatter. The formatter returned directly by
630      * this method will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}.
631      * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
632      * on the result of this method.
633      * <p>
634      * Note that the localized pattern is looked up lazily.
635      * This {@code DateTimeFormatter} holds the style required and the locale,
636      * looking up the pattern required on demand.
637      * <p>
638      * The returned formatter has a chronology of ISO set to ensure dates in
639      * other calendar systems are correctly converted.
640      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
641      * The {@code FULL} and {@code LONG} styles typically require a time-zone.
642      * When formatting using these styles, a {@code ZoneId} must be available,
643      * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}.
644      *
645      * @param timeStyle  the formatter style to obtain, not null
646      * @return the time formatter, not null
647      */
ofLocalizedTime(FormatStyle timeStyle)648     public static DateTimeFormatter ofLocalizedTime(FormatStyle timeStyle) {
649         Objects.requireNonNull(timeStyle, "timeStyle");
650         return new DateTimeFormatterBuilder().appendLocalized(null, timeStyle)
651                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
652     }
653 
654     /**
655      * Returns a locale specific date-time formatter for the ISO chronology.
656      * <p>
657      * This returns a formatter that will format or parse a date-time.
658      * The exact format pattern used varies by locale.
659      * <p>
660      * The locale is determined from the formatter. The formatter returned directly by
661      * this method will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}.
662      * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
663      * on the result of this method.
664      * <p>
665      * Note that the localized pattern is looked up lazily.
666      * This {@code DateTimeFormatter} holds the style required and the locale,
667      * looking up the pattern required on demand.
668      * <p>
669      * The returned formatter has a chronology of ISO set to ensure dates in
670      * other calendar systems are correctly converted.
671      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
672      * The {@code FULL} and {@code LONG} styles typically require a time-zone.
673      * When formatting using these styles, a {@code ZoneId} must be available,
674      * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}.
675      *
676      * @param dateTimeStyle  the formatter style to obtain, not null
677      * @return the date-time formatter, not null
678      */
ofLocalizedDateTime(FormatStyle dateTimeStyle)679     public static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateTimeStyle) {
680         Objects.requireNonNull(dateTimeStyle, "dateTimeStyle");
681         return new DateTimeFormatterBuilder().appendLocalized(dateTimeStyle, dateTimeStyle)
682                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
683     }
684 
685     /**
686      * Returns a locale specific date and time format for the ISO chronology.
687      * <p>
688      * This returns a formatter that will format or parse a date-time.
689      * The exact format pattern used varies by locale.
690      * <p>
691      * The locale is determined from the formatter. The formatter returned directly by
692      * this method will use the {@link Locale#getDefault() default FORMAT locale}.
693      * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
694      * on the result of this method.
695      * <p>
696      * Note that the localized pattern is looked up lazily.
697      * This {@code DateTimeFormatter} holds the style required and the locale,
698      * looking up the pattern required on demand.
699      * <p>
700      * The returned formatter has a chronology of ISO set to ensure dates in
701      * other calendar systems are correctly converted.
702      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
703      * The {@code FULL} and {@code LONG} styles typically require a time-zone.
704      * When formatting using these styles, a {@code ZoneId} must be available,
705      * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}.
706      *
707      * @param dateStyle  the date formatter style to obtain, not null
708      * @param timeStyle  the time formatter style to obtain, not null
709      * @return the date, time or date-time formatter, not null
710      */
ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle)711     public static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle) {
712         Objects.requireNonNull(dateStyle, "dateStyle");
713         Objects.requireNonNull(timeStyle, "timeStyle");
714         return new DateTimeFormatterBuilder().appendLocalized(dateStyle, timeStyle)
715                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
716     }
717 
718     //-----------------------------------------------------------------------
719     /**
720      * The ISO date formatter that formats or parses a date without an
721      * offset, such as '2011-12-03'.
722      * <p>
723      * This returns an immutable formatter capable of formatting and parsing
724      * the ISO-8601 extended local date format.
725      * The format consists of:
726      * <ul>
727      * <li>Four digits or more for the {@link ChronoField#YEAR year}.
728      * Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits.
729      * Years outside that range will have a prefixed positive or negative symbol.
730      * <li>A dash
731      * <li>Two digits for the {@link ChronoField#MONTH_OF_YEAR month-of-year}.
732      *  This is pre-padded by zero to ensure two digits.
733      * <li>A dash
734      * <li>Two digits for the {@link ChronoField#DAY_OF_MONTH day-of-month}.
735      *  This is pre-padded by zero to ensure two digits.
736      * </ul>
737      * <p>
738      * The returned formatter has a chronology of ISO set to ensure dates in
739      * other calendar systems are correctly converted.
740      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
741      */
742     public static final DateTimeFormatter ISO_LOCAL_DATE;
743     static {
744         ISO_LOCAL_DATE = new DateTimeFormatterBuilder()
745                 .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
746                 .appendLiteral('-')
747                 .appendValue(MONTH_OF_YEAR, 2)
748                 .appendLiteral('-')
749                 .appendValue(DAY_OF_MONTH, 2)
750                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
751     }
752 
753     //-----------------------------------------------------------------------
754     /**
755      * The ISO date formatter that formats or parses a date with an
756      * offset, such as '2011-12-03+01:00'.
757      * <p>
758      * This returns an immutable formatter capable of formatting and parsing
759      * the ISO-8601 extended offset date format.
760      * The format consists of:
761      * <ul>
762      * <li>The {@link #ISO_LOCAL_DATE}
763      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
764      *  they will be handled even though this is not part of the ISO-8601 standard.
765      *  Parsing is case insensitive.
766      * </ul>
767      * <p>
768      * The returned formatter has a chronology of ISO set to ensure dates in
769      * other calendar systems are correctly converted.
770      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
771      */
772     public static final DateTimeFormatter ISO_OFFSET_DATE;
773     static {
774         ISO_OFFSET_DATE = new DateTimeFormatterBuilder()
775                 .parseCaseInsensitive()
776                 .append(ISO_LOCAL_DATE)
777                 .appendOffsetId()
778                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
779     }
780 
781     //-----------------------------------------------------------------------
782     /**
783      * The ISO date formatter that formats or parses a date with the
784      * offset if available, such as '2011-12-03' or '2011-12-03+01:00'.
785      * <p>
786      * This returns an immutable formatter capable of formatting and parsing
787      * the ISO-8601 extended date format.
788      * The format consists of:
789      * <ul>
790      * <li>The {@link #ISO_LOCAL_DATE}
791      * <li>If the offset is not available then the format is complete.
792      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
793      *  they will be handled even though this is not part of the ISO-8601 standard.
794      *  Parsing is case insensitive.
795      * </ul>
796      * <p>
797      * As this formatter has an optional element, it may be necessary to parse using
798      * {@link DateTimeFormatter#parseBest}.
799      * <p>
800      * The returned formatter has a chronology of ISO set to ensure dates in
801      * other calendar systems are correctly converted.
802      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
803      */
804     public static final DateTimeFormatter ISO_DATE;
805     static {
806         ISO_DATE = new DateTimeFormatterBuilder()
807                 .parseCaseInsensitive()
808                 .append(ISO_LOCAL_DATE)
809                 .optionalStart()
810                 .appendOffsetId()
811                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
812     }
813 
814     //-----------------------------------------------------------------------
815     /**
816      * The ISO time formatter that formats or parses a time without an
817      * offset, such as '10:15' or '10:15:30'.
818      * <p>
819      * This returns an immutable formatter capable of formatting and parsing
820      * the ISO-8601 extended local time format.
821      * The format consists of:
822      * <ul>
823      * <li>Two digits for the {@link ChronoField#HOUR_OF_DAY hour-of-day}.
824      *  This is pre-padded by zero to ensure two digits.
825      * <li>A colon
826      * <li>Two digits for the {@link ChronoField#MINUTE_OF_HOUR minute-of-hour}.
827      *  This is pre-padded by zero to ensure two digits.
828      * <li>If the second-of-minute is not available then the format is complete.
829      * <li>A colon
830      * <li>Two digits for the {@link ChronoField#SECOND_OF_MINUTE second-of-minute}.
831      *  This is pre-padded by zero to ensure two digits.
832      * <li>If the nano-of-second is zero or not available then the format is complete.
833      * <li>A decimal point
834      * <li>One to nine digits for the {@link ChronoField#NANO_OF_SECOND nano-of-second}.
835      *  As many digits will be output as required.
836      * </ul>
837      * <p>
838      * The returned formatter has no override chronology or zone.
839      * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
840      */
841     public static final DateTimeFormatter ISO_LOCAL_TIME;
842     static {
843         ISO_LOCAL_TIME = new DateTimeFormatterBuilder()
844                 .appendValue(HOUR_OF_DAY, 2)
845                 .appendLiteral(':')
846                 .appendValue(MINUTE_OF_HOUR, 2)
847                 .optionalStart()
848                 .appendLiteral(':')
849                 .appendValue(SECOND_OF_MINUTE, 2)
850                 .optionalStart()
851                 .appendFraction(NANO_OF_SECOND, 0, 9, true)
852                 .toFormatter(ResolverStyle.STRICT, null);
853     }
854 
855     //-----------------------------------------------------------------------
856     /**
857      * The ISO time formatter that formats or parses a time with an
858      * offset, such as '10:15+01:00' or '10:15:30+01:00'.
859      * <p>
860      * This returns an immutable formatter capable of formatting and parsing
861      * the ISO-8601 extended offset time format.
862      * The format consists of:
863      * <ul>
864      * <li>The {@link #ISO_LOCAL_TIME}
865      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
866      *  they will be handled even though this is not part of the ISO-8601 standard.
867      *  Parsing is case insensitive.
868      * </ul>
869      * <p>
870      * The returned formatter has no override chronology or zone.
871      * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
872      */
873     public static final DateTimeFormatter ISO_OFFSET_TIME;
874     static {
875         ISO_OFFSET_TIME = new DateTimeFormatterBuilder()
876                 .parseCaseInsensitive()
877                 .append(ISO_LOCAL_TIME)
878                 .appendOffsetId()
879                 .toFormatter(ResolverStyle.STRICT, null);
880     }
881 
882     //-----------------------------------------------------------------------
883     /**
884      * The ISO time formatter that formats or parses a time, with the
885      * offset if available, such as '10:15', '10:15:30' or '10:15:30+01:00'.
886      * <p>
887      * This returns an immutable formatter capable of formatting and parsing
888      * the ISO-8601 extended offset time format.
889      * The format consists of:
890      * <ul>
891      * <li>The {@link #ISO_LOCAL_TIME}
892      * <li>If the offset is not available then the format is complete.
893      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
894      *  they will be handled even though this is not part of the ISO-8601 standard.
895      *  Parsing is case insensitive.
896      * </ul>
897      * <p>
898      * As this formatter has an optional element, it may be necessary to parse using
899      * {@link DateTimeFormatter#parseBest}.
900      * <p>
901      * The returned formatter has no override chronology or zone.
902      * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
903      */
904     public static final DateTimeFormatter ISO_TIME;
905     static {
906         ISO_TIME = new DateTimeFormatterBuilder()
907                 .parseCaseInsensitive()
908                 .append(ISO_LOCAL_TIME)
909                 .optionalStart()
910                 .appendOffsetId()
911                 .toFormatter(ResolverStyle.STRICT, null);
912     }
913 
914     //-----------------------------------------------------------------------
915     /**
916      * The ISO date-time formatter that formats or parses a date-time without
917      * an offset, such as '2011-12-03T10:15:30'.
918      * <p>
919      * This returns an immutable formatter capable of formatting and parsing
920      * the ISO-8601 extended offset date-time format.
921      * The format consists of:
922      * <ul>
923      * <li>The {@link #ISO_LOCAL_DATE}
924      * <li>The letter 'T'. Parsing is case insensitive.
925      * <li>The {@link #ISO_LOCAL_TIME}
926      * </ul>
927      * <p>
928      * The returned formatter has a chronology of ISO set to ensure dates in
929      * other calendar systems are correctly converted.
930      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
931      */
932     public static final DateTimeFormatter ISO_LOCAL_DATE_TIME;
933     static {
934         ISO_LOCAL_DATE_TIME = new DateTimeFormatterBuilder()
935                 .parseCaseInsensitive()
936                 .append(ISO_LOCAL_DATE)
937                 .appendLiteral('T')
938                 .append(ISO_LOCAL_TIME)
939                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
940     }
941 
942     //-----------------------------------------------------------------------
943     /**
944      * The ISO date-time formatter that formats or parses a date-time with an
945      * offset, such as '2011-12-03T10:15:30+01:00'.
946      * <p>
947      * This returns an immutable formatter capable of formatting and parsing
948      * the ISO-8601 extended offset date-time format.
949      * The format consists of:
950      * <ul>
951      * <li>The {@link #ISO_LOCAL_DATE_TIME}
952      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
953      *  they will be handled even though this is not part of the ISO-8601 standard.
954      *  The offset parsing is lenient, which allows the minutes and seconds to be optional.
955      *  Parsing is case insensitive.
956      * </ul>
957      * <p>
958      * The returned formatter has a chronology of ISO set to ensure dates in
959      * other calendar systems are correctly converted.
960      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
961      */
962     public static final DateTimeFormatter ISO_OFFSET_DATE_TIME;
963     static {
964         ISO_OFFSET_DATE_TIME = new DateTimeFormatterBuilder()
965                 .parseCaseInsensitive()
966                 .append(ISO_LOCAL_DATE_TIME)
967                 .parseLenient()
968                 .appendOffsetId()
969                 .parseStrict()
970                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
971     }
972 
973     //-----------------------------------------------------------------------
974     /**
975      * The ISO-like date-time formatter that formats or parses a date-time with
976      * offset and zone, such as '2011-12-03T10:15:30+01:00[Europe/Paris]'.
977      * <p>
978      * This returns an immutable formatter capable of formatting and parsing
979      * a format that extends the ISO-8601 extended offset date-time format
980      * to add the time-zone.
981      * The section in square brackets is not part of the ISO-8601 standard.
982      * The format consists of:
983      * <ul>
984      * <li>The {@link #ISO_OFFSET_DATE_TIME}
985      * <li>If the zone ID is not available or is a {@code ZoneOffset} then the format is complete.
986      * <li>An open square bracket '['.
987      * <li>The {@link ZoneId#getId() zone ID}. This is not part of the ISO-8601 standard.
988      *  Parsing is case sensitive.
989      * <li>A close square bracket ']'.
990      * </ul>
991      * <p>
992      * The returned formatter has a chronology of ISO set to ensure dates in
993      * other calendar systems are correctly converted.
994      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
995      */
996     public static final DateTimeFormatter ISO_ZONED_DATE_TIME;
997     static {
998         ISO_ZONED_DATE_TIME = new DateTimeFormatterBuilder()
999                 .append(ISO_OFFSET_DATE_TIME)
1000                 .optionalStart()
1001                 .appendLiteral('[')
1002                 .parseCaseSensitive()
1003                 .appendZoneRegionId()
1004                 .appendLiteral(']')
1005                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1006     }
1007 
1008     //-----------------------------------------------------------------------
1009     /**
1010      * The ISO-like date-time formatter that formats or parses a date-time with
1011      * the offset and zone if available, such as '2011-12-03T10:15:30',
1012      * '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'.
1013      * <p>
1014      * This returns an immutable formatter capable of formatting and parsing
1015      * the ISO-8601 extended local or offset date-time format, as well as the
1016      * extended non-ISO form specifying the time-zone.
1017      * The format consists of:
1018      * <ul>
1019      * <li>The {@link #ISO_LOCAL_DATE_TIME}
1020      * <li>If the offset is not available to format or parse then the format is complete.
1021      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
1022      *  they will be handled even though this is not part of the ISO-8601 standard.
1023      * <li>If the zone ID is not available or is a {@code ZoneOffset} then the format is complete.
1024      * <li>An open square bracket '['.
1025      * <li>The {@link ZoneId#getId() zone ID}. This is not part of the ISO-8601 standard.
1026      *  Parsing is case sensitive.
1027      * <li>A close square bracket ']'.
1028      * </ul>
1029      * <p>
1030      * As this formatter has an optional element, it may be necessary to parse using
1031      * {@link DateTimeFormatter#parseBest}.
1032      * <p>
1033      * The returned formatter has a chronology of ISO set to ensure dates in
1034      * other calendar systems are correctly converted.
1035      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1036      */
1037     public static final DateTimeFormatter ISO_DATE_TIME;
1038     static {
1039         ISO_DATE_TIME = new DateTimeFormatterBuilder()
1040                 .append(ISO_LOCAL_DATE_TIME)
1041                 .optionalStart()
1042                 .appendOffsetId()
1043                 .optionalStart()
1044                 .appendLiteral('[')
1045                 .parseCaseSensitive()
1046                 .appendZoneRegionId()
1047                 .appendLiteral(']')
1048                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1049     }
1050 
1051     //-----------------------------------------------------------------------
1052     /**
1053      * The ISO date formatter that formats or parses the ordinal date
1054      * without an offset, such as '2012-337'.
1055      * <p>
1056      * This returns an immutable formatter capable of formatting and parsing
1057      * the ISO-8601 extended ordinal date format.
1058      * The format consists of:
1059      * <ul>
1060      * <li>Four digits or more for the {@link ChronoField#YEAR year}.
1061      * Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits.
1062      * Years outside that range will have a prefixed positive or negative symbol.
1063      * <li>A dash
1064      * <li>Three digits for the {@link ChronoField#DAY_OF_YEAR day-of-year}.
1065      *  This is pre-padded by zero to ensure three digits.
1066      * <li>If the offset is not available to format or parse then the format is complete.
1067      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
1068      *  they will be handled even though this is not part of the ISO-8601 standard.
1069      *  Parsing is case insensitive.
1070      * </ul>
1071      * <p>
1072      * As this formatter has an optional element, it may be necessary to parse using
1073      * {@link DateTimeFormatter#parseBest}.
1074      * <p>
1075      * The returned formatter has a chronology of ISO set to ensure dates in
1076      * other calendar systems are correctly converted.
1077      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1078      */
1079     public static final DateTimeFormatter ISO_ORDINAL_DATE;
1080     static {
1081         ISO_ORDINAL_DATE = new DateTimeFormatterBuilder()
1082                 .parseCaseInsensitive()
1083                 .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
1084                 .appendLiteral('-')
1085                 .appendValue(DAY_OF_YEAR, 3)
1086                 .optionalStart()
1087                 .appendOffsetId()
1088                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1089     }
1090 
1091     //-----------------------------------------------------------------------
1092     /**
1093      * The ISO date formatter that formats or parses the week-based date
1094      * without an offset, such as '2012-W48-6'.
1095      * <p>
1096      * This returns an immutable formatter capable of formatting and parsing
1097      * the ISO-8601 extended week-based date format.
1098      * The format consists of:
1099      * <ul>
1100      * <li>Four digits or more for the {@link IsoFields#WEEK_BASED_YEAR week-based-year}.
1101      * Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits.
1102      * Years outside that range will have a prefixed positive or negative symbol.
1103      * <li>A dash
1104      * <li>The letter 'W'. Parsing is case insensitive.
1105      * <li>Two digits for the {@link IsoFields#WEEK_OF_WEEK_BASED_YEAR week-of-week-based-year}.
1106      *  This is pre-padded by zero to ensure three digits.
1107      * <li>A dash
1108      * <li>One digit for the {@link ChronoField#DAY_OF_WEEK day-of-week}.
1109      *  The value run from Monday (1) to Sunday (7).
1110      * <li>If the offset is not available to format or parse then the format is complete.
1111      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
1112      *  they will be handled even though this is not part of the ISO-8601 standard.
1113      *  Parsing is case insensitive.
1114      * </ul>
1115      * <p>
1116      * As this formatter has an optional element, it may be necessary to parse using
1117      * {@link DateTimeFormatter#parseBest}.
1118      * <p>
1119      * The returned formatter has a chronology of ISO set to ensure dates in
1120      * other calendar systems are correctly converted.
1121      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1122      */
1123     public static final DateTimeFormatter ISO_WEEK_DATE;
1124     static {
1125         ISO_WEEK_DATE = new DateTimeFormatterBuilder()
1126                 .parseCaseInsensitive()
1127                 .appendValue(IsoFields.WEEK_BASED_YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
1128                 .appendLiteral("-W")
1129                 .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2)
1130                 .appendLiteral('-')
1131                 .appendValue(DAY_OF_WEEK, 1)
1132                 .optionalStart()
1133                 .appendOffsetId()
1134                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1135     }
1136 
1137     //-----------------------------------------------------------------------
1138     /**
1139      * The ISO instant formatter that formats or parses an instant in UTC,
1140      * such as '2011-12-03T10:15:30Z'.
1141      * <p>
1142      * This returns an immutable formatter capable of formatting and parsing
1143      * the ISO-8601 instant format.
1144      * When formatting, the instant will always be suffixed by 'Z' to indicate UTC.
1145      * The second-of-minute is always output.
1146      * The nano-of-second outputs zero, three, six or nine digits as necessary.
1147      * When parsing, the behaviour of {@link DateTimeFormatterBuilder#appendOffsetId()}
1148      * will be used to parse the offset, converting the instant to UTC as necessary.
1149      * The time to at least the seconds field is required.
1150      * Fractional seconds from zero to nine are parsed.
1151      * The localized decimal style is not used.
1152      * <p>
1153      * This is a special case formatter intended to allow a human readable form
1154      * of an {@link java.time.Instant}. The {@code Instant} class is designed to
1155      * only represent a point in time and internally stores a value in nanoseconds
1156      * from a fixed epoch of 1970-01-01Z. As such, an {@code Instant} cannot be
1157      * formatted as a date or time without providing some form of time-zone.
1158      * This formatter allows the {@code Instant} to be formatted, by providing
1159      * a suitable conversion using {@code ZoneOffset.UTC}.
1160      * <p>
1161      * The format consists of:
1162      * <ul>
1163      * <li>The {@link #ISO_OFFSET_DATE_TIME} where the instant is converted from
1164      *  {@link ChronoField#INSTANT_SECONDS} and {@link ChronoField#NANO_OF_SECOND}
1165      *  using the {@code UTC} offset. Parsing is case insensitive.
1166      * </ul>
1167      * <p>
1168      * The returned formatter has no override chronology or zone.
1169      * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1170      */
1171     public static final DateTimeFormatter ISO_INSTANT;
1172     static {
1173         ISO_INSTANT = new DateTimeFormatterBuilder()
1174                 .parseCaseInsensitive()
1175                 .appendInstant()
1176                 .toFormatter(ResolverStyle.STRICT, null);
1177     }
1178 
1179     //-----------------------------------------------------------------------
1180     /**
1181      * The ISO date formatter that formats or parses a date without an
1182      * offset, such as '20111203'.
1183      * <p>
1184      * This returns an immutable formatter capable of formatting and parsing
1185      * the ISO-8601 basic local date format.
1186      * The format consists of:
1187      * <ul>
1188      * <li>Four digits for the {@link ChronoField#YEAR year}.
1189      *  Only years in the range 0000 to 9999 are supported.
1190      * <li>Two digits for the {@link ChronoField#MONTH_OF_YEAR month-of-year}.
1191      *  This is pre-padded by zero to ensure two digits.
1192      * <li>Two digits for the {@link ChronoField#DAY_OF_MONTH day-of-month}.
1193      *  This is pre-padded by zero to ensure two digits.
1194      * <li>If the offset is not available to format or parse then the format is complete.
1195      * <li>The {@link ZoneOffset#getId() offset ID} without colons. If the offset has
1196      *  seconds then they will be handled even though this is not part of the ISO-8601 standard.
1197      *  The offset parsing is lenient, which allows the minutes and seconds to be optional.
1198      *  Parsing is case insensitive.
1199      * </ul>
1200      * <p>
1201      * As this formatter has an optional element, it may be necessary to parse using
1202      * {@link DateTimeFormatter#parseBest}.
1203      * <p>
1204      * The returned formatter has a chronology of ISO set to ensure dates in
1205      * other calendar systems are correctly converted.
1206      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1207      */
1208     public static final DateTimeFormatter BASIC_ISO_DATE;
1209     static {
1210         BASIC_ISO_DATE = new DateTimeFormatterBuilder()
1211                 .parseCaseInsensitive()
1212                 .appendValue(YEAR, 4)
1213                 .appendValue(MONTH_OF_YEAR, 2)
1214                 .appendValue(DAY_OF_MONTH, 2)
1215                 .optionalStart()
1216                 .parseLenient()
1217                 .appendOffset("+HHMMss", "Z")
1218                 .parseStrict()
1219                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1220     }
1221 
1222     //-----------------------------------------------------------------------
1223     /**
1224      * The RFC-1123 date-time formatter, such as 'Tue, 3 Jun 2008 11:05:30 GMT'.
1225      * <p>
1226      * This returns an immutable formatter capable of formatting and parsing
1227      * most of the RFC-1123 format.
1228      * RFC-1123 updates RFC-822 changing the year from two digits to four.
1229      * This implementation requires a four digit year.
1230      * This implementation also does not handle North American or military zone
1231      * names, only 'GMT' and offset amounts.
1232      * <p>
1233      * The format consists of:
1234      * <ul>
1235      * <li>If the day-of-week is not available to format or parse then jump to day-of-month.
1236      * <li>Three letter {@link ChronoField#DAY_OF_WEEK day-of-week} in English.
1237      * <li>A comma
1238      * <li>A space
1239      * <li>One or two digits for the {@link ChronoField#DAY_OF_MONTH day-of-month}.
1240      * <li>A space
1241      * <li>Three letter {@link ChronoField#MONTH_OF_YEAR month-of-year} in English.
1242      * <li>A space
1243      * <li>Four digits for the {@link ChronoField#YEAR year}.
1244      *  Only years in the range 0000 to 9999 are supported.
1245      * <li>A space
1246      * <li>Two digits for the {@link ChronoField#HOUR_OF_DAY hour-of-day}.
1247      *  This is pre-padded by zero to ensure two digits.
1248      * <li>A colon
1249      * <li>Two digits for the {@link ChronoField#MINUTE_OF_HOUR minute-of-hour}.
1250      *  This is pre-padded by zero to ensure two digits.
1251      * <li>If the second-of-minute is not available then jump to the next space.
1252      * <li>A colon
1253      * <li>Two digits for the {@link ChronoField#SECOND_OF_MINUTE second-of-minute}.
1254      *  This is pre-padded by zero to ensure two digits.
1255      * <li>A space
1256      * <li>The {@link ZoneOffset#getId() offset ID} without colons or seconds.
1257      *  An offset of zero uses "GMT". North American zone names and military zone names are not handled.
1258      * </ul>
1259      * <p>
1260      * Parsing is case insensitive.
1261      * <p>
1262      * The returned formatter has a chronology of ISO set to ensure dates in
1263      * other calendar systems are correctly converted.
1264      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
1265      */
1266     public static final DateTimeFormatter RFC_1123_DATE_TIME;
1267     static {
1268         // manually code maps to ensure correct data always used
1269         // (locale data can be changed by application code)
1270         Map<Long, String> dow = new HashMap<>();
1271         dow.put(1L, "Mon");
1272         dow.put(2L, "Tue");
1273         dow.put(3L, "Wed");
1274         dow.put(4L, "Thu");
1275         dow.put(5L, "Fri");
1276         dow.put(6L, "Sat");
1277         dow.put(7L, "Sun");
1278         Map<Long, String> moy = new HashMap<>();
1279         moy.put(1L, "Jan");
1280         moy.put(2L, "Feb");
1281         moy.put(3L, "Mar");
1282         moy.put(4L, "Apr");
1283         moy.put(5L, "May");
1284         moy.put(6L, "Jun");
1285         moy.put(7L, "Jul");
1286         moy.put(8L, "Aug");
1287         moy.put(9L, "Sep");
1288         moy.put(10L, "Oct");
1289         moy.put(11L, "Nov");
1290         moy.put(12L, "Dec");
1291         RFC_1123_DATE_TIME = new DateTimeFormatterBuilder()
1292                 .parseCaseInsensitive()
1293                 .parseLenient()
1294                 .optionalStart()
1295                 .appendText(DAY_OF_WEEK, dow)
1296                 .appendLiteral(", ")
1297                 .optionalEnd()
1298                 .appendValue(DAY_OF_MONTH, 1, 2, SignStyle.NOT_NEGATIVE)
1299                 .appendLiteral(' ')
1300                 .appendText(MONTH_OF_YEAR, moy)
1301                 .appendLiteral(' ')
1302                 .appendValue(YEAR, 4)  // 2 digit year not handled
1303                 .appendLiteral(' ')
1304                 .appendValue(HOUR_OF_DAY, 2)
1305                 .appendLiteral(':')
1306                 .appendValue(MINUTE_OF_HOUR, 2)
1307                 .optionalStart()
1308                 .appendLiteral(':')
1309                 .appendValue(SECOND_OF_MINUTE, 2)
1310                 .optionalEnd()
1311                 .appendLiteral(' ')
1312                 .appendOffset("+HHMM", "GMT")  // should handle UT/Z/EST/EDT/CST/CDT/MST/MDT/PST/MDT
1313                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
1314     }
1315 
1316     //-----------------------------------------------------------------------
1317     /**
1318      * A query that provides access to the excess days that were parsed.
1319      * <p>
1320      * This returns a singleton {@linkplain TemporalQuery query} that provides
1321      * access to additional information from the parse. The query always returns
1322      * a non-null period, with a zero period returned instead of null.
1323      * <p>
1324      * There are two situations where this query may return a non-zero period.
1325      * <ul>
1326      * <li>If the {@code ResolverStyle} is {@code LENIENT} and a time is parsed
1327      *  without a date, then the complete result of the parse consists of a
1328      *  {@code LocalTime} and an excess {@code Period} in days.
1329      *
1330      * <li>If the {@code ResolverStyle} is {@code SMART} and a time is parsed
1331      *  without a date where the time is 24:00:00, then the complete result of
1332      *  the parse consists of a {@code LocalTime} of 00:00:00 and an excess
1333      *  {@code Period} of one day.
1334      * </ul>
1335      * <p>
1336      * In both cases, if a complete {@code ChronoLocalDateTime} or {@code Instant}
1337      * is parsed, then the excess days are added to the date part.
1338      * As a result, this query will return a zero period.
1339      * <p>
1340      * The {@code SMART} behaviour handles the common "end of day" 24:00 value.
1341      * Processing in {@code LENIENT} mode also produces the same result:
1342      * <pre>
1343      *  Text to parse        Parsed object                         Excess days
1344      *  "2012-12-03T00:00"   LocalDateTime.of(2012, 12, 3, 0, 0)   ZERO
1345      *  "2012-12-03T24:00"   LocalDateTime.of(2012, 12, 4, 0, 0)   ZERO
1346      *  "00:00"              LocalTime.of(0, 0)                    ZERO
1347      *  "24:00"              LocalTime.of(0, 0)                    Period.ofDays(1)
1348      * </pre>
1349      * The query can be used as follows:
1350      * <pre>
1351      *  TemporalAccessor parsed = formatter.parse(str);
1352      *  LocalTime time = parsed.query(LocalTime::from);
1353      *  Period extraDays = parsed.query(DateTimeFormatter.parsedExcessDays());
1354      * </pre>
1355      * @return a query that provides access to the excess days that were parsed
1356      */
parsedExcessDays()1357     public static final TemporalQuery<Period> parsedExcessDays() {
1358         return PARSED_EXCESS_DAYS;
1359     }
1360     private static final TemporalQuery<Period> PARSED_EXCESS_DAYS = t -> {
1361         if (t instanceof Parsed) {
1362             return ((Parsed) t).excessDays;
1363         } else {
1364             return Period.ZERO;
1365         }
1366     };
1367 
1368     /**
1369      * A query that provides access to whether a leap-second was parsed.
1370      * <p>
1371      * This returns a singleton {@linkplain TemporalQuery query} that provides
1372      * access to additional information from the parse. The query always returns
1373      * a non-null boolean, true if parsing saw a leap-second, false if not.
1374      * <p>
1375      * Instant parsing handles the special "leap second" time of '23:59:60'.
1376      * Leap seconds occur at '23:59:60' in the UTC time-zone, but at other
1377      * local times in different time-zones. To avoid this potential ambiguity,
1378      * the handling of leap-seconds is limited to
1379      * {@link DateTimeFormatterBuilder#appendInstant()}, as that method
1380      * always parses the instant with the UTC zone offset.
1381      * <p>
1382      * If the time '23:59:60' is received, then a simple conversion is applied,
1383      * replacing the second-of-minute of 60 with 59. This query can be used
1384      * on the parse result to determine if the leap-second adjustment was made.
1385      * The query will return {@code true} if it did adjust to remove the
1386      * leap-second, and {@code false} if not. Note that applying a leap-second
1387      * smoothing mechanism, such as UTC-SLS, is the responsibility of the
1388      * application, as follows:
1389      * <pre>
1390      *  TemporalAccessor parsed = formatter.parse(str);
1391      *  Instant instant = parsed.query(Instant::from);
1392      *  if (parsed.query(DateTimeFormatter.parsedLeapSecond())) {
1393      *    // validate leap-second is correct and apply correct smoothing
1394      *  }
1395      * </pre>
1396      * @return a query that provides access to whether a leap-second was parsed
1397      */
parsedLeapSecond()1398     public static final TemporalQuery<Boolean> parsedLeapSecond() {
1399         return PARSED_LEAP_SECOND;
1400     }
1401     private static final TemporalQuery<Boolean> PARSED_LEAP_SECOND = t -> {
1402         if (t instanceof Parsed) {
1403             return ((Parsed) t).leapSecond;
1404         } else {
1405             return Boolean.FALSE;
1406         }
1407     };
1408 
1409     //-----------------------------------------------------------------------
1410     /**
1411      * Constructor.
1412      *
1413      * @param printerParser  the printer/parser to use, not null
1414      * @param locale  the locale to use, not null
1415      * @param decimalStyle  the DecimalStyle to use, not null
1416      * @param resolverStyle  the resolver style to use, not null
1417      * @param resolverFields  the fields to use during resolving, null for all fields
1418      * @param chrono  the chronology to use, null for no override
1419      * @param zone  the zone to use, null for no override
1420      */
DateTimeFormatter(CompositePrinterParser printerParser, Locale locale, DecimalStyle decimalStyle, ResolverStyle resolverStyle, Set<TemporalField> resolverFields, Chronology chrono, ZoneId zone)1421     DateTimeFormatter(CompositePrinterParser printerParser,
1422             Locale locale, DecimalStyle decimalStyle,
1423             ResolverStyle resolverStyle, Set<TemporalField> resolverFields,
1424             Chronology chrono, ZoneId zone) {
1425         this.printerParser = Objects.requireNonNull(printerParser, "printerParser");
1426         this.resolverFields = resolverFields;
1427         this.locale = Objects.requireNonNull(locale, "locale");
1428         this.decimalStyle = Objects.requireNonNull(decimalStyle, "decimalStyle");
1429         this.resolverStyle = Objects.requireNonNull(resolverStyle, "resolverStyle");
1430         this.chrono = chrono;
1431         this.zone = zone;
1432     }
1433 
1434     //-----------------------------------------------------------------------
1435     /**
1436      * Gets the locale to be used during formatting.
1437      * <p>
1438      * This is used to lookup any part of the formatter needing specific
1439      * localization, such as the text or localized pattern.
1440      *
1441      * @return the locale of this formatter, not null
1442      */
getLocale()1443     public Locale getLocale() {
1444         return locale;
1445     }
1446 
1447     // Android-changed: Remove javadoc reference to #localizedBy(Locale)
1448     /**
1449      * Returns a copy of this formatter with a new locale.
1450      * <p>
1451      * This is used to lookup any part of the formatter needing specific
1452      * localization, such as the text or localized pattern.
1453      * <p>
1454      * The locale is stored as passed in, without further processing.
1455      * <p>
1456      * This instance is immutable and unaffected by this method call.
1457      *
1458      * @param locale  the new locale, not null
1459      * @return a formatter based on this formatter with the requested locale, not null
1460      */
withLocale(Locale locale)1461     public DateTimeFormatter withLocale(Locale locale) {
1462         if (this.locale.equals(locale)) {
1463             return this;
1464         }
1465         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1466     }
1467 
1468     // Android-changed: Remove "rg" extension support in the javadoc. See http://b/228322300.
1469     /**
1470      * Returns a copy of this formatter with localized values of the locale,
1471      * calendar, decimal style and/or timezone, that superseded values in
1472      * this formatter.
1473      * <p>
1474      * This is used to lookup any part of the formatter needing specific
1475      * localization, such as the text or localized pattern. If the locale contains the
1476      * "ca" (calendar), "nu" (numbering system) and/or
1477      * "tz" (timezone)
1478      * <a href="../../util/Locale.html#def_locale_extension">Unicode extensions</a>,
1479      * the chronology, numbering system and/or the zone are overridden.
1480      * <p>
1481      * Unlike the {@link #withLocale withLocale} method, the call to this method may
1482      * produce a different formatter depending on the order of method chaining with
1483      * other withXXXX() methods.
1484      * <p>
1485      * This instance is immutable and unaffected by this method call.
1486      *
1487      * @param locale  the locale, not null
1488      * @return a formatter based on this formatter with localized values of
1489      *      the calendar, decimal style and/or timezone, that superseded values in this
1490      *      formatter.
1491      * @see #withLocale(Locale)
1492      * @since 10
1493      */
localizedBy(Locale locale)1494     public DateTimeFormatter localizedBy(Locale locale) {
1495         // Override decimalStyle/chronology/timezone for the locale object
1496         String tzType = locale.getUnicodeLocaleType("tz");
1497         ZoneId z  = tzType != null ?
1498                     // Android changed: Use ICU on Android.
1499                     // TimeZoneNameUtility.convertLDMLShortID(tzType)
1500                     Optional.ofNullable(ICU.convertToTzId(tzType))
1501                         .map(ZoneId::of)
1502                         .orElse(zone) :
1503                     zone;
1504         Chronology c = Chronology.ofLocale(locale);
1505         DecimalStyle ds = DecimalStyle.of(locale);
1506         if (this.locale.equals(locale) &&
1507                 c.equals(chrono) &&
1508                 ds.equals(decimalStyle) &&
1509                 Objects.equals(z, zone)) {
1510             return this;
1511         } else {
1512             return new DateTimeFormatter(printerParser, locale, ds, resolverStyle, resolverFields, c, z);
1513         }
1514     }
1515 
1516     //-----------------------------------------------------------------------
1517     /**
1518      * Gets the DecimalStyle to be used during formatting.
1519      *
1520      * @return the locale of this formatter, not null
1521      */
getDecimalStyle()1522     public DecimalStyle getDecimalStyle() {
1523         return decimalStyle;
1524     }
1525 
1526     /**
1527      * Returns a copy of this formatter with a new DecimalStyle.
1528      * <p>
1529      * This instance is immutable and unaffected by this method call.
1530      *
1531      * @param decimalStyle  the new DecimalStyle, not null
1532      * @return a formatter based on this formatter with the requested DecimalStyle, not null
1533      */
withDecimalStyle(DecimalStyle decimalStyle)1534     public DateTimeFormatter withDecimalStyle(DecimalStyle decimalStyle) {
1535         if (this.decimalStyle.equals(decimalStyle)) {
1536             return this;
1537         }
1538         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1539     }
1540 
1541     //-----------------------------------------------------------------------
1542     /**
1543      * Gets the overriding chronology to be used during formatting.
1544      * <p>
1545      * This returns the override chronology, used to convert dates.
1546      * By default, a formatter has no override chronology, returning null.
1547      * See {@link #withChronology(Chronology)} for more details on overriding.
1548      *
1549      * @return the override chronology of this formatter, null if no override
1550      */
getChronology()1551     public Chronology getChronology() {
1552         return chrono;
1553     }
1554 
1555     /**
1556      * Returns a copy of this formatter with a new override chronology.
1557      * <p>
1558      * This returns a formatter with similar state to this formatter but
1559      * with the override chronology set.
1560      * By default, a formatter has no override chronology, returning null.
1561      * <p>
1562      * If an override is added, then any date that is formatted or parsed will be affected.
1563      * <p>
1564      * When formatting, if the temporal object contains a date, then it will
1565      * be converted to a date in the override chronology.
1566      * Whether the temporal contains a date is determined by querying the
1567      * {@link ChronoField#EPOCH_DAY EPOCH_DAY} field.
1568      * Any time or zone will be retained unaltered unless overridden.
1569      * <p>
1570      * If the temporal object does not contain a date, but does contain one
1571      * or more {@code ChronoField} date fields, then a {@code DateTimeException}
1572      * is thrown. In all other cases, the override chronology is added to the temporal,
1573      * replacing any previous chronology, but without changing the date/time.
1574      * <p>
1575      * When parsing, there are two distinct cases to consider.
1576      * If a chronology has been parsed directly from the text, perhaps because
1577      * {@link DateTimeFormatterBuilder#appendChronologyId()} was used, then
1578      * this override chronology has no effect.
1579      * If no zone has been parsed, then this override chronology will be used
1580      * to interpret the {@code ChronoField} values into a date according to the
1581      * date resolving rules of the chronology.
1582      * <p>
1583      * This instance is immutable and unaffected by this method call.
1584      *
1585      * @param chrono  the new chronology, null if no override
1586      * @return a formatter based on this formatter with the requested override chronology, not null
1587      */
withChronology(Chronology chrono)1588     public DateTimeFormatter withChronology(Chronology chrono) {
1589         if (Objects.equals(this.chrono, chrono)) {
1590             return this;
1591         }
1592         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1593     }
1594 
1595     //-----------------------------------------------------------------------
1596     /**
1597      * Gets the overriding zone to be used during formatting.
1598      * <p>
1599      * This returns the override zone, used to convert instants.
1600      * By default, a formatter has no override zone, returning null.
1601      * See {@link #withZone(ZoneId)} for more details on overriding.
1602      *
1603      * @return the override zone of this formatter, null if no override
1604      */
getZone()1605     public ZoneId getZone() {
1606         return zone;
1607     }
1608 
1609     /**
1610      * Returns a copy of this formatter with a new override zone.
1611      * <p>
1612      * This returns a formatter with similar state to this formatter but
1613      * with the override zone set.
1614      * By default, a formatter has no override zone, returning null.
1615      * <p>
1616      * If an override is added, then any instant that is formatted or parsed will be affected.
1617      * <p>
1618      * When formatting, if the temporal object contains an instant, then it will
1619      * be converted to a zoned date-time using the override zone.
1620      * Whether the temporal is an instant is determined by querying the
1621      * {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS} field.
1622      * If the input has a chronology then it will be retained unless overridden.
1623      * If the input does not have a chronology, such as {@code Instant}, then
1624      * the ISO chronology will be used.
1625      * <p>
1626      * If the temporal object does not contain an instant, but does contain
1627      * an offset then an additional check is made. If the normalized override
1628      * zone is an offset that differs from the offset of the temporal, then
1629      * a {@code DateTimeException} is thrown. In all other cases, the override
1630      * zone is added to the temporal, replacing any previous zone, but without
1631      * changing the date/time.
1632      * <p>
1633      * When parsing, there are two distinct cases to consider.
1634      * If a zone has been parsed directly from the text, perhaps because
1635      * {@link DateTimeFormatterBuilder#appendZoneId()} was used, then
1636      * this override zone has no effect.
1637      * If no zone has been parsed, then this override zone will be included in
1638      * the result of the parse where it can be used to build instants and date-times.
1639      * <p>
1640      * This instance is immutable and unaffected by this method call.
1641      *
1642      * @param zone  the new override zone, null if no override
1643      * @return a formatter based on this formatter with the requested override zone, not null
1644      */
withZone(ZoneId zone)1645     public DateTimeFormatter withZone(ZoneId zone) {
1646         if (Objects.equals(this.zone, zone)) {
1647             return this;
1648         }
1649         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1650     }
1651 
1652     //-----------------------------------------------------------------------
1653     /**
1654      * Gets the resolver style to use during parsing.
1655      * <p>
1656      * This returns the resolver style, used during the second phase of parsing
1657      * when fields are resolved into dates and times.
1658      * By default, a formatter has the {@link ResolverStyle#SMART SMART} resolver style.
1659      * See {@link #withResolverStyle(ResolverStyle)} for more details.
1660      *
1661      * @return the resolver style of this formatter, not null
1662      */
getResolverStyle()1663     public ResolverStyle getResolverStyle() {
1664         return resolverStyle;
1665     }
1666 
1667     /**
1668      * Returns a copy of this formatter with a new resolver style.
1669      * <p>
1670      * This returns a formatter with similar state to this formatter but
1671      * with the resolver style set. By default, a formatter has the
1672      * {@link ResolverStyle#SMART SMART} resolver style.
1673      * <p>
1674      * Changing the resolver style only has an effect during parsing.
1675      * Parsing a text string occurs in two phases.
1676      * Phase 1 is a basic text parse according to the fields added to the builder.
1677      * Phase 2 resolves the parsed field-value pairs into date and/or time objects.
1678      * The resolver style is used to control how phase 2, resolving, happens.
1679      * See {@code ResolverStyle} for more information on the options available.
1680      * <p>
1681      * This instance is immutable and unaffected by this method call.
1682      *
1683      * @param resolverStyle  the new resolver style, not null
1684      * @return a formatter based on this formatter with the requested resolver style, not null
1685      */
withResolverStyle(ResolverStyle resolverStyle)1686     public DateTimeFormatter withResolverStyle(ResolverStyle resolverStyle) {
1687         Objects.requireNonNull(resolverStyle, "resolverStyle");
1688         if (Objects.equals(this.resolverStyle, resolverStyle)) {
1689             return this;
1690         }
1691         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1692     }
1693 
1694     //-----------------------------------------------------------------------
1695     /**
1696      * Gets the resolver fields to use during parsing.
1697      * <p>
1698      * This returns the resolver fields, used during the second phase of parsing
1699      * when fields are resolved into dates and times.
1700      * By default, a formatter has no resolver fields, and thus returns null.
1701      * See {@link #withResolverFields(Set)} for more details.
1702      *
1703      * @return the immutable set of resolver fields of this formatter, null if no fields
1704      */
getResolverFields()1705     public Set<TemporalField> getResolverFields() {
1706         return resolverFields;
1707     }
1708 
1709     /**
1710      * Returns a copy of this formatter with a new set of resolver fields.
1711      * <p>
1712      * This returns a formatter with similar state to this formatter but with
1713      * the resolver fields set. By default, a formatter has no resolver fields.
1714      * <p>
1715      * Changing the resolver fields only has an effect during parsing.
1716      * Parsing a text string occurs in two phases.
1717      * Phase 1 is a basic text parse according to the fields added to the builder.
1718      * Phase 2 resolves the parsed field-value pairs into date and/or time objects.
1719      * The resolver fields are used to filter the field-value pairs between phase 1 and 2.
1720      * <p>
1721      * This can be used to select between two or more ways that a date or time might
1722      * be resolved. For example, if the formatter consists of year, month, day-of-month
1723      * and day-of-year, then there are two ways to resolve a date.
1724      * Calling this method with the arguments {@link ChronoField#YEAR YEAR} and
1725      * {@link ChronoField#DAY_OF_YEAR DAY_OF_YEAR} will ensure that the date is
1726      * resolved using the year and day-of-year, effectively meaning that the month
1727      * and day-of-month are ignored during the resolving phase.
1728      * <p>
1729      * In a similar manner, this method can be used to ignore secondary fields that
1730      * would otherwise be cross-checked. For example, if the formatter consists of year,
1731      * month, day-of-month and day-of-week, then there is only one way to resolve a
1732      * date, but the parsed value for day-of-week will be cross-checked against the
1733      * resolved date. Calling this method with the arguments {@link ChronoField#YEAR YEAR},
1734      * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and
1735      * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} will ensure that the date is
1736      * resolved correctly, but without any cross-check for the day-of-week.
1737      * <p>
1738      * In implementation terms, this method behaves as follows. The result of the
1739      * parsing phase can be considered to be a map of field to value. The behavior
1740      * of this method is to cause that map to be filtered between phase 1 and 2,
1741      * removing all fields other than those specified as arguments to this method.
1742      * <p>
1743      * This instance is immutable and unaffected by this method call.
1744      *
1745      * @param resolverFields  the new set of resolver fields, null if no fields
1746      * @return a formatter based on this formatter with the requested resolver style, not null
1747      */
withResolverFields(TemporalField... resolverFields)1748     public DateTimeFormatter withResolverFields(TemporalField... resolverFields) {
1749         Set<TemporalField> fields = null;
1750         if (resolverFields != null) {
1751             // Set.of cannot be used because it is hostile to nulls and duplicate elements
1752             fields = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(resolverFields)));
1753         }
1754         if (Objects.equals(this.resolverFields, fields)) {
1755             return this;
1756         }
1757         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, fields, chrono, zone);
1758     }
1759 
1760     /**
1761      * Returns a copy of this formatter with a new set of resolver fields.
1762      * <p>
1763      * This returns a formatter with similar state to this formatter but with
1764      * the resolver fields set. By default, a formatter has no resolver fields.
1765      * <p>
1766      * Changing the resolver fields only has an effect during parsing.
1767      * Parsing a text string occurs in two phases.
1768      * Phase 1 is a basic text parse according to the fields added to the builder.
1769      * Phase 2 resolves the parsed field-value pairs into date and/or time objects.
1770      * The resolver fields are used to filter the field-value pairs between phase 1 and 2.
1771      * <p>
1772      * This can be used to select between two or more ways that a date or time might
1773      * be resolved. For example, if the formatter consists of year, month, day-of-month
1774      * and day-of-year, then there are two ways to resolve a date.
1775      * Calling this method with the arguments {@link ChronoField#YEAR YEAR} and
1776      * {@link ChronoField#DAY_OF_YEAR DAY_OF_YEAR} will ensure that the date is
1777      * resolved using the year and day-of-year, effectively meaning that the month
1778      * and day-of-month are ignored during the resolving phase.
1779      * <p>
1780      * In a similar manner, this method can be used to ignore secondary fields that
1781      * would otherwise be cross-checked. For example, if the formatter consists of year,
1782      * month, day-of-month and day-of-week, then there is only one way to resolve a
1783      * date, but the parsed value for day-of-week will be cross-checked against the
1784      * resolved date. Calling this method with the arguments {@link ChronoField#YEAR YEAR},
1785      * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and
1786      * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} will ensure that the date is
1787      * resolved correctly, but without any cross-check for the day-of-week.
1788      * <p>
1789      * In implementation terms, this method behaves as follows. The result of the
1790      * parsing phase can be considered to be a map of field to value. The behavior
1791      * of this method is to cause that map to be filtered between phase 1 and 2,
1792      * removing all fields other than those specified as arguments to this method.
1793      * <p>
1794      * This instance is immutable and unaffected by this method call.
1795      *
1796      * @param resolverFields  the new set of resolver fields, null if no fields
1797      * @return a formatter based on this formatter with the requested resolver style, not null
1798      */
withResolverFields(Set<TemporalField> resolverFields)1799     public DateTimeFormatter withResolverFields(Set<TemporalField> resolverFields) {
1800         if (Objects.equals(this.resolverFields, resolverFields)) {
1801             return this;
1802         }
1803         if (resolverFields != null) {
1804             resolverFields = Collections.unmodifiableSet(new HashSet<>(resolverFields));
1805         }
1806         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1807     }
1808 
1809     //-----------------------------------------------------------------------
1810     /**
1811      * Formats a date-time object using this formatter.
1812      * <p>
1813      * This formats the date-time to a String using the rules of the formatter.
1814      *
1815      * @param temporal  the temporal object to format, not null
1816      * @return the formatted string, not null
1817      * @throws DateTimeException if an error occurs during formatting
1818      */
format(TemporalAccessor temporal)1819     public String format(TemporalAccessor temporal) {
1820         StringBuilder buf = new StringBuilder(32);
1821         formatTo(temporal, buf);
1822         return buf.toString();
1823     }
1824 
1825     //-----------------------------------------------------------------------
1826     /**
1827      * Formats a date-time object to an {@code Appendable} using this formatter.
1828      * <p>
1829      * This outputs the formatted date-time to the specified destination.
1830      * {@link Appendable} is a general purpose interface that is implemented by all
1831      * key character output classes including {@code StringBuffer}, {@code StringBuilder},
1832      * {@code PrintStream} and {@code Writer}.
1833      * <p>
1834      * Although {@code Appendable} methods throw an {@code IOException}, this method does not.
1835      * Instead, any {@code IOException} is wrapped in a runtime exception.
1836      *
1837      * @param temporal  the temporal object to format, not null
1838      * @param appendable  the appendable to format to, not null
1839      * @throws DateTimeException if an error occurs during formatting
1840      */
formatTo(TemporalAccessor temporal, Appendable appendable)1841     public void formatTo(TemporalAccessor temporal, Appendable appendable) {
1842         Objects.requireNonNull(temporal, "temporal");
1843         Objects.requireNonNull(appendable, "appendable");
1844         try {
1845             DateTimePrintContext context = new DateTimePrintContext(temporal, this);
1846             if (appendable instanceof StringBuilder) {
1847                 printerParser.format(context, (StringBuilder) appendable);
1848             } else {
1849                 // buffer output to avoid writing to appendable in case of error
1850                 StringBuilder buf = new StringBuilder(32);
1851                 printerParser.format(context, buf);
1852                 appendable.append(buf);
1853             }
1854         } catch (IOException ex) {
1855             throw new DateTimeException(ex.getMessage(), ex);
1856         }
1857     }
1858 
1859     //-----------------------------------------------------------------------
1860     /**
1861      * Fully parses the text producing a temporal object.
1862      * <p>
1863      * This parses the entire text producing a temporal object.
1864      * It is typically more useful to use {@link #parse(CharSequence, TemporalQuery)}.
1865      * The result of this method is {@code TemporalAccessor} which has been resolved,
1866      * applying basic validation checks to help ensure a valid date-time.
1867      * <p>
1868      * If the parse completes without reading the entire length of the text,
1869      * or a problem occurs during parsing or merging, then an exception is thrown.
1870      *
1871      * @param text  the text to parse, not null
1872      * @return the parsed temporal object, not null
1873      * @throws DateTimeParseException if unable to parse the requested result
1874      */
parse(CharSequence text)1875     public TemporalAccessor parse(CharSequence text) {
1876         Objects.requireNonNull(text, "text");
1877         try {
1878             return parseResolved0(text, null);
1879         } catch (DateTimeParseException ex) {
1880             throw ex;
1881         } catch (RuntimeException ex) {
1882             throw createError(text, ex);
1883         }
1884     }
1885 
1886     /**
1887      * Parses the text using this formatter, providing control over the text position.
1888      * <p>
1889      * This parses the text without requiring the parse to start from the beginning
1890      * of the string or finish at the end.
1891      * The result of this method is {@code TemporalAccessor} which has been resolved,
1892      * applying basic validation checks to help ensure a valid date-time.
1893      * <p>
1894      * The text will be parsed from the specified start {@code ParsePosition}.
1895      * The entire length of the text does not have to be parsed, the {@code ParsePosition}
1896      * will be updated with the index at the end of parsing.
1897      * <p>
1898      * The operation of this method is slightly different to similar methods using
1899      * {@code ParsePosition} on {@code java.text.Format}. That class will return
1900      * errors using the error index on the {@code ParsePosition}. By contrast, this
1901      * method will throw a {@link DateTimeParseException} if an error occurs, with
1902      * the exception containing the error index.
1903      * This change in behavior is necessary due to the increased complexity of
1904      * parsing and resolving dates/times in this API.
1905      * <p>
1906      * If the formatter parses the same field more than once with different values,
1907      * the result will be an error.
1908      *
1909      * @param text  the text to parse, not null
1910      * @param position  the position to parse from, updated with length parsed
1911      *  and the index of any error, not null
1912      * @return the parsed temporal object, not null
1913      * @throws DateTimeParseException if unable to parse the requested result
1914      * @throws IndexOutOfBoundsException if the position is invalid
1915      */
parse(CharSequence text, ParsePosition position)1916     public TemporalAccessor parse(CharSequence text, ParsePosition position) {
1917         Objects.requireNonNull(text, "text");
1918         Objects.requireNonNull(position, "position");
1919         try {
1920             return parseResolved0(text, position);
1921         } catch (DateTimeParseException | IndexOutOfBoundsException ex) {
1922             throw ex;
1923         } catch (RuntimeException ex) {
1924             throw createError(text, ex);
1925         }
1926     }
1927 
1928     //-----------------------------------------------------------------------
1929     /**
1930      * Fully parses the text producing an object of the specified type.
1931      * <p>
1932      * Most applications should use this method for parsing.
1933      * It parses the entire text to produce the required date-time.
1934      * The query is typically a method reference to a {@code from(TemporalAccessor)} method.
1935      * For example:
1936      * <pre>
1937      *  LocalDateTime dt = parser.parse(str, LocalDateTime::from);
1938      * </pre>
1939      * If the parse completes without reading the entire length of the text,
1940      * or a problem occurs during parsing or merging, then an exception is thrown.
1941      *
1942      * @param <T> the type of the parsed date-time
1943      * @param text  the text to parse, not null
1944      * @param query  the query defining the type to parse to, not null
1945      * @return the parsed date-time, not null
1946      * @throws DateTimeParseException if unable to parse the requested result
1947      */
parse(CharSequence text, TemporalQuery<T> query)1948     public <T> T parse(CharSequence text, TemporalQuery<T> query) {
1949         Objects.requireNonNull(text, "text");
1950         Objects.requireNonNull(query, "query");
1951         try {
1952             return parseResolved0(text, null).query(query);
1953         } catch (DateTimeParseException ex) {
1954             throw ex;
1955         } catch (RuntimeException ex) {
1956             throw createError(text, ex);
1957         }
1958     }
1959 
1960     /**
1961      * Fully parses the text producing an object of one of the specified types.
1962      * <p>
1963      * This parse method is convenient for use when the parser can handle optional elements.
1964      * For example, a pattern of 'uuuu-MM-dd HH.mm[ VV]' can be fully parsed to a {@code ZonedDateTime},
1965      * or partially parsed to a {@code LocalDateTime}.
1966      * The queries must be specified in order, starting from the best matching full-parse option
1967      * and ending with the worst matching minimal parse option.
1968      * The query is typically a method reference to a {@code from(TemporalAccessor)} method.
1969      * <p>
1970      * The result is associated with the first type that successfully parses.
1971      * Normally, applications will use {@code instanceof} to check the result.
1972      * For example:
1973      * <pre>
1974      *  TemporalAccessor dt = parser.parseBest(str, ZonedDateTime::from, LocalDateTime::from);
1975      *  if (dt instanceof ZonedDateTime) {
1976      *   ...
1977      *  } else {
1978      *   ...
1979      *  }
1980      * </pre>
1981      * If the parse completes without reading the entire length of the text,
1982      * or a problem occurs during parsing or merging, then an exception is thrown.
1983      *
1984      * @param text  the text to parse, not null
1985      * @param queries  the queries defining the types to attempt to parse to,
1986      *  must implement {@code TemporalAccessor}, not null
1987      * @return the parsed date-time, not null
1988      * @throws IllegalArgumentException if less than 2 types are specified
1989      * @throws DateTimeParseException if unable to parse the requested result
1990      */
parseBest(CharSequence text, TemporalQuery<?>... queries)1991     public TemporalAccessor parseBest(CharSequence text, TemporalQuery<?>... queries) {
1992         Objects.requireNonNull(text, "text");
1993         Objects.requireNonNull(queries, "queries");
1994         if (queries.length < 2) {
1995             throw new IllegalArgumentException("At least two queries must be specified");
1996         }
1997         try {
1998             TemporalAccessor resolved = parseResolved0(text, null);
1999             for (TemporalQuery<?> query : queries) {
2000                 try {
2001                     return (TemporalAccessor) resolved.query(query);
2002                 } catch (RuntimeException ex) {
2003                     // continue
2004                 }
2005             }
2006             throw new DateTimeException("Unable to convert parsed text using any of the specified queries");
2007         } catch (DateTimeParseException ex) {
2008             throw ex;
2009         } catch (RuntimeException ex) {
2010             throw createError(text, ex);
2011         }
2012     }
2013 
createError(CharSequence text, RuntimeException ex)2014     private DateTimeParseException createError(CharSequence text, RuntimeException ex) {
2015         String abbr;
2016         if (text.length() > 64) {
2017             abbr = text.subSequence(0, 64).toString() + "...";
2018         } else {
2019             abbr = text.toString();
2020         }
2021         return new DateTimeParseException("Text '" + abbr + "' could not be parsed: " + ex.getMessage(), text, 0, ex);
2022     }
2023 
2024     //-----------------------------------------------------------------------
2025     /**
2026      * Parses and resolves the specified text.
2027      * <p>
2028      * This parses to a {@code TemporalAccessor} ensuring that the text is fully parsed.
2029      *
2030      * @param text  the text to parse, not null
2031      * @param position  the position to parse from, updated with length parsed
2032      *  and the index of any error, null if parsing whole string
2033      * @return the resolved result of the parse, not null
2034      * @throws DateTimeParseException if the parse fails
2035      * @throws DateTimeException if an error occurs while resolving the date or time
2036      * @throws IndexOutOfBoundsException if the position is invalid
2037      */
parseResolved0(final CharSequence text, final ParsePosition position)2038     private TemporalAccessor parseResolved0(final CharSequence text, final ParsePosition position) {
2039         ParsePosition pos = (position != null ? position : new ParsePosition(0));
2040         DateTimeParseContext context = parseUnresolved0(text, pos);
2041         if (context == null || pos.getErrorIndex() >= 0 || (position == null && pos.getIndex() < text.length())) {
2042             String abbr;
2043             if (text.length() > 64) {
2044                 abbr = text.subSequence(0, 64).toString() + "...";
2045             } else {
2046                 abbr = text.toString();
2047             }
2048             if (pos.getErrorIndex() >= 0) {
2049                 throw new DateTimeParseException("Text '" + abbr + "' could not be parsed at index " +
2050                         pos.getErrorIndex(), text, pos.getErrorIndex());
2051             } else {
2052                 throw new DateTimeParseException("Text '" + abbr + "' could not be parsed, unparsed text found at index " +
2053                         pos.getIndex(), text, pos.getIndex());
2054             }
2055         }
2056         return context.toResolved(resolverStyle, resolverFields);
2057     }
2058 
2059     /**
2060      * Parses the text using this formatter, without resolving the result, intended
2061      * for advanced use cases.
2062      * <p>
2063      * Parsing is implemented as a two-phase operation.
2064      * First, the text is parsed using the layout defined by the formatter, producing
2065      * a {@code Map} of field to value, a {@code ZoneId} and a {@code Chronology}.
2066      * Second, the parsed data is <em>resolved</em>, by validating, combining and
2067      * simplifying the various fields into more useful ones.
2068      * This method performs the parsing stage but not the resolving stage.
2069      * <p>
2070      * The result of this method is {@code TemporalAccessor} which represents the
2071      * data as seen in the input. Values are not validated, thus parsing a date string
2072      * of '2012-00-65' would result in a temporal with three fields - year of '2012',
2073      * month of '0' and day-of-month of '65'.
2074      * <p>
2075      * The text will be parsed from the specified start {@code ParsePosition}.
2076      * The entire length of the text does not have to be parsed, the {@code ParsePosition}
2077      * will be updated with the index at the end of parsing.
2078      * <p>
2079      * Errors are returned using the error index field of the {@code ParsePosition}
2080      * instead of {@code DateTimeParseException}.
2081      * The returned error index will be set to an index indicative of the error.
2082      * Callers must check for errors before using the result.
2083      * <p>
2084      * If the formatter parses the same field more than once with different values,
2085      * the result will be an error.
2086      * <p>
2087      * This method is intended for advanced use cases that need access to the
2088      * internal state during parsing. Typical application code should use
2089      * {@link #parse(CharSequence, TemporalQuery)} or the parse method on the target type.
2090      *
2091      * @param text  the text to parse, not null
2092      * @param position  the position to parse from, updated with length parsed
2093      *  and the index of any error, not null
2094      * @return the parsed text, null if the parse results in an error
2095      * @throws DateTimeException if some problem occurs during parsing
2096      * @throws IndexOutOfBoundsException if the position is invalid
2097      */
parseUnresolved(CharSequence text, ParsePosition position)2098     public TemporalAccessor parseUnresolved(CharSequence text, ParsePosition position) {
2099         DateTimeParseContext context = parseUnresolved0(text, position);
2100         if (context == null) {
2101             return null;
2102         }
2103         return context.toUnresolved();
2104     }
2105 
parseUnresolved0(CharSequence text, ParsePosition position)2106     private DateTimeParseContext parseUnresolved0(CharSequence text, ParsePosition position) {
2107         Objects.requireNonNull(text, "text");
2108         Objects.requireNonNull(position, "position");
2109         DateTimeParseContext context = new DateTimeParseContext(this);
2110         int pos = position.getIndex();
2111         pos = printerParser.parse(context, text, pos);
2112         if (pos < 0) {
2113             position.setErrorIndex(~pos);  // index not updated from input
2114             return null;
2115         }
2116         position.setIndex(pos);  // errorIndex not updated from input
2117         return context;
2118     }
2119 
2120     //-----------------------------------------------------------------------
2121     /**
2122      * Returns the formatter as a composite printer parser.
2123      *
2124      * @param optional  whether the printer/parser should be optional
2125      * @return the printer/parser, not null
2126      */
toPrinterParser(boolean optional)2127     CompositePrinterParser toPrinterParser(boolean optional) {
2128         return printerParser.withOptional(optional);
2129     }
2130 
2131     /**
2132      * Returns this formatter as a {@code java.text.Format} instance.
2133      * <p>
2134      * The returned {@link Format} instance will format any {@link TemporalAccessor}
2135      * and parses to a resolved {@link TemporalAccessor}.
2136      * <p>
2137      * Exceptions will follow the definitions of {@code Format}, see those methods
2138      * for details about {@code IllegalArgumentException} during formatting and
2139      * {@code ParseException} or null during parsing.
2140      * The format does not support attributing of the returned format string.
2141      *
2142      * @return this formatter as a classic format instance, not null
2143      */
toFormat()2144     public Format toFormat() {
2145         return new ClassicFormat(this, null);
2146     }
2147 
2148     /**
2149      * Returns this formatter as a {@code java.text.Format} instance that will
2150      * parse using the specified query.
2151      * <p>
2152      * The returned {@link Format} instance will format any {@link TemporalAccessor}
2153      * and parses to the type specified.
2154      * The type must be one that is supported by {@link #parse}.
2155      * <p>
2156      * Exceptions will follow the definitions of {@code Format}, see those methods
2157      * for details about {@code IllegalArgumentException} during formatting and
2158      * {@code ParseException} or null during parsing.
2159      * The format does not support attributing of the returned format string.
2160      *
2161      * @param parseQuery  the query defining the type to parse to, not null
2162      * @return this formatter as a classic format instance, not null
2163      */
toFormat(TemporalQuery<?> parseQuery)2164     public Format toFormat(TemporalQuery<?> parseQuery) {
2165         Objects.requireNonNull(parseQuery, "parseQuery");
2166         return new ClassicFormat(this, parseQuery);
2167     }
2168 
2169     //-----------------------------------------------------------------------
2170     /**
2171      * Returns a description of the underlying formatters.
2172      *
2173      * @return a description of this formatter, not null
2174      */
2175     @Override
toString()2176     public String toString() {
2177         String pattern = printerParser.toString();
2178         pattern = pattern.startsWith("[") ? pattern : pattern.substring(1, pattern.length() - 1);
2179         return pattern;
2180         // TODO: Fix tests to not depend on toString()
2181 //        return "DateTimeFormatter[" + locale +
2182 //                (chrono != null ? "," + chrono : "") +
2183 //                (zone != null ? "," + zone : "") +
2184 //                pattern + "]";
2185     }
2186 
2187     //-----------------------------------------------------------------------
2188     /**
2189      * Implements the classic Java Format API.
2190      * @serial exclude
2191      */
2192     @SuppressWarnings("serial")  // not actually serializable
2193     static class ClassicFormat extends Format {
2194         /** The formatter. */
2195         private final DateTimeFormatter formatter;
2196         /** The type to be parsed. */
2197         private final TemporalQuery<?> parseType;
2198         /** Constructor. */
ClassicFormat(DateTimeFormatter formatter, TemporalQuery<?> parseType)2199         public ClassicFormat(DateTimeFormatter formatter, TemporalQuery<?> parseType) {
2200             this.formatter = formatter;
2201             this.parseType = parseType;
2202         }
2203 
2204         @Override
format(Object obj, StringBuffer toAppendTo, FieldPosition pos)2205         public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
2206             Objects.requireNonNull(obj, "obj");
2207             Objects.requireNonNull(toAppendTo, "toAppendTo");
2208             Objects.requireNonNull(pos, "pos");
2209             if (!(obj instanceof TemporalAccessor)) {
2210                 throw new IllegalArgumentException("Format target must implement TemporalAccessor");
2211             }
2212             pos.setBeginIndex(0);
2213             pos.setEndIndex(0);
2214             try {
2215                 formatter.formatTo((TemporalAccessor) obj, toAppendTo);
2216             } catch (RuntimeException ex) {
2217                 throw new IllegalArgumentException(ex.getMessage(), ex);
2218             }
2219             return toAppendTo;
2220         }
2221         @Override
parseObject(String text)2222         public Object parseObject(String text) throws ParseException {
2223             Objects.requireNonNull(text, "text");
2224             try {
2225                 if (parseType == null) {
2226                     return formatter.parseResolved0(text, null);
2227                 }
2228                 return formatter.parse(text, parseType);
2229             } catch (DateTimeParseException ex) {
2230                 throw new ParseException(ex.getMessage(), ex.getErrorIndex());
2231             } catch (RuntimeException ex) {
2232                 throw (ParseException) new ParseException(ex.getMessage(), 0).initCause(ex);
2233             }
2234         }
2235         @Override
parseObject(String text, ParsePosition pos)2236         public Object parseObject(String text, ParsePosition pos) {
2237             Objects.requireNonNull(text, "text");
2238             DateTimeParseContext context;
2239             try {
2240                 context = formatter.parseUnresolved0(text, pos);
2241             } catch (IndexOutOfBoundsException ex) {
2242                 if (pos.getErrorIndex() < 0) {
2243                     pos.setErrorIndex(0);
2244                 }
2245                 return null;
2246             }
2247             if (context == null) {
2248                 if (pos.getErrorIndex() < 0) {
2249                     pos.setErrorIndex(0);
2250                 }
2251                 return null;
2252             }
2253             try {
2254                 TemporalAccessor resolved = context.toResolved(formatter.resolverStyle, formatter.resolverFields);
2255                 if (parseType == null) {
2256                     return resolved;
2257                 }
2258                 return resolved.query(parseType);
2259             } catch (RuntimeException ex) {
2260                 pos.setErrorIndex(0);
2261                 return null;
2262             }
2263         }
2264     }
2265 
2266 }
2267