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