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      *
 623      * @param timeStyle  the formatter style to obtain, not null
 624      * @return the time formatter, not null
 625      */
 626     public static DateTimeFormatter ofLocalizedTime(FormatStyle timeStyle) {
 627         Objects.requireNonNull(timeStyle, "timeStyle");
 628         return new DateTimeFormatterBuilder().appendLocalized(null, timeStyle)
 629                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
 630     }
 631 
 632     /**
 633      * Returns a locale specific date-time formatter for the ISO chronology.
 634      * <p>
 635      * This returns a formatter that will format or parse a date-time.
 636      * The exact format pattern used varies by locale.
 637      * <p>
 638      * The locale is determined from the formatter. The formatter returned directly by
 639      * this method will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}.
 640      * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
 641      * on the result of this method.
 642      * <p>
 643      * Note that the localized pattern is looked up lazily.
 644      * This {@code DateTimeFormatter} holds the style required and the locale,
 645      * looking up the pattern required on demand.
 646      * <p>
 647      * The returned formatter has a chronology of ISO set to ensure dates in
 648      * other calendar systems are correctly converted.
 649      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
 650      *
 651      * @param dateTimeStyle  the formatter style to obtain, not null
 652      * @return the date-time formatter, not null
 653      */
 654     public static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateTimeStyle) {
 655         Objects.requireNonNull(dateTimeStyle, "dateTimeStyle");
 656         return new DateTimeFormatterBuilder().appendLocalized(dateTimeStyle, dateTimeStyle)
 657                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
 658     }
 659 
 660     /**
 661      * Returns a locale specific date and time format for the ISO chronology.
 662      * <p>
 663      * This returns a formatter that will format or parse a date-time.
 664      * The exact format pattern used varies by locale.
 665      * <p>
 666      * The locale is determined from the formatter. The formatter returned directly by
 667      * this method will use the {@link Locale#getDefault() default FORMAT locale}.
 668      * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
 669      * on the result of this method.
 670      * <p>
 671      * Note that the localized pattern is looked up lazily.
 672      * This {@code DateTimeFormatter} holds the style required and the locale,
 673      * looking up the pattern required on demand.
 674      * <p>
 675      * The returned formatter has a chronology of ISO set to ensure dates in
 676      * other calendar systems are correctly converted.
 677      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
 678      *
 679      * @param dateStyle  the date formatter style to obtain, not null
 680      * @param timeStyle  the time formatter style to obtain, not null
 681      * @return the date, time or date-time formatter, not null
 682      */
 683     public static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle) {
 684         Objects.requireNonNull(dateStyle, "dateStyle");
 685         Objects.requireNonNull(timeStyle, "timeStyle");
 686         return new DateTimeFormatterBuilder().appendLocalized(dateStyle, timeStyle)
 687                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
 688     }
 689 
 690     //-----------------------------------------------------------------------
 691     /**
 692      * The ISO date formatter that formats or parses a date without an
 693      * offset, such as '2011-12-03'.
 694      * <p>
 695      * This returns an immutable formatter capable of formatting and parsing
 696      * the ISO-8601 extended local date format.
 697      * The format consists of:
 698      * <ul>
 699      * <li>Four digits or more for the {@link ChronoField#YEAR year}.
 700      * Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits.
 701      * Years outside that range will have a prefixed positive or negative symbol.
 702      * <li>A dash
 703      * <li>Two digits for the {@link ChronoField#MONTH_OF_YEAR month-of-year}.
 704      *  This is pre-padded by zero to ensure two digits.
 705      * <li>A dash
 706      * <li>Two digits for the {@link ChronoField#DAY_OF_MONTH day-of-month}.
 707      *  This is pre-padded by zero to ensure two digits.
 708      * </ul>
 709      * <p>
 710      * The returned formatter has a chronology of ISO set to ensure dates in
 711      * other calendar systems are correctly converted.
 712      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 713      */
 714     public static final DateTimeFormatter ISO_LOCAL_DATE;
 715     static {
 716         ISO_LOCAL_DATE = new DateTimeFormatterBuilder()
 717                 .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
 718                 .appendLiteral('-')
 719                 .appendValue(MONTH_OF_YEAR, 2)
 720                 .appendLiteral('-')
 721                 .appendValue(DAY_OF_MONTH, 2)
 722                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
 723     }
 724 
 725     //-----------------------------------------------------------------------
 726     /**
 727      * The ISO date formatter that formats or parses a date with an
 728      * offset, such as '2011-12-03+01:00'.
 729      * <p>
 730      * This returns an immutable formatter capable of formatting and parsing
 731      * the ISO-8601 extended offset date format.
 732      * The format consists of:
 733      * <ul>
 734      * <li>The {@link #ISO_LOCAL_DATE}
 735      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
 736      *  they will be handled even though this is not part of the ISO-8601 standard.
 737      *  Parsing is case insensitive.
 738      * </ul>
 739      * <p>
 740      * The returned formatter has a chronology of ISO set to ensure dates in
 741      * other calendar systems are correctly converted.
 742      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 743      */
 744     public static final DateTimeFormatter ISO_OFFSET_DATE;
 745     static {
 746         ISO_OFFSET_DATE = new DateTimeFormatterBuilder()
 747                 .parseCaseInsensitive()
 748                 .append(ISO_LOCAL_DATE)
 749                 .appendOffsetId()
 750                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
 751     }
 752 
 753     //-----------------------------------------------------------------------
 754     /**
 755      * The ISO date formatter that formats or parses a date with the
 756      * offset if available, such as '2011-12-03' or '2011-12-03+01:00'.
 757      * <p>
 758      * This returns an immutable formatter capable of formatting and parsing
 759      * the ISO-8601 extended date format.
 760      * The format consists of:
 761      * <ul>
 762      * <li>The {@link #ISO_LOCAL_DATE}
 763      * <li>If the offset is not available then the format is complete.
 764      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
 765      *  they will be handled even though this is not part of the ISO-8601 standard.
 766      *  Parsing is case insensitive.
 767      * </ul>
 768      * <p>
 769      * As this formatter has an optional element, it may be necessary to parse using
 770      * {@link DateTimeFormatter#parseBest}.
 771      * <p>
 772      * The returned formatter has a chronology of ISO set to ensure dates in
 773      * other calendar systems are correctly converted.
 774      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 775      */
 776     public static final DateTimeFormatter ISO_DATE;
 777     static {
 778         ISO_DATE = new DateTimeFormatterBuilder()
 779                 .parseCaseInsensitive()
 780                 .append(ISO_LOCAL_DATE)
 781                 .optionalStart()
 782                 .appendOffsetId()
 783                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
 784     }
 785 
 786     //-----------------------------------------------------------------------
 787     /**
 788      * The ISO time formatter that formats or parses a time without an
 789      * offset, such as '10:15' or '10:15:30'.
 790      * <p>
 791      * This returns an immutable formatter capable of formatting and parsing
 792      * the ISO-8601 extended local time format.
 793      * The format consists of:
 794      * <ul>
 795      * <li>Two digits for the {@link ChronoField#HOUR_OF_DAY hour-of-day}.
 796      *  This is pre-padded by zero to ensure two digits.
 797      * <li>A colon
 798      * <li>Two digits for the {@link ChronoField#MINUTE_OF_HOUR minute-of-hour}.
 799      *  This is pre-padded by zero to ensure two digits.
 800      * <li>If the second-of-minute is not available then the format is complete.
 801      * <li>A colon
 802      * <li>Two digits for the {@link ChronoField#SECOND_OF_MINUTE second-of-minute}.
 803      *  This is pre-padded by zero to ensure two digits.
 804      * <li>If the nano-of-second is zero or not available then the format is complete.
 805      * <li>A decimal point
 806      * <li>One to nine digits for the {@link ChronoField#NANO_OF_SECOND nano-of-second}.
 807      *  As many digits will be output as required.
 808      * </ul>
 809      * <p>
 810      * The returned formatter has no override chronology or zone.
 811      * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 812      */
 813     public static final DateTimeFormatter ISO_LOCAL_TIME;
 814     static {
 815         ISO_LOCAL_TIME = new DateTimeFormatterBuilder()
 816                 .appendValue(HOUR_OF_DAY, 2)
 817                 .appendLiteral(':')
 818                 .appendValue(MINUTE_OF_HOUR, 2)
 819                 .optionalStart()
 820                 .appendLiteral(':')
 821                 .appendValue(SECOND_OF_MINUTE, 2)
 822                 .optionalStart()
 823                 .appendFraction(NANO_OF_SECOND, 0, 9, true)
 824                 .toFormatter(ResolverStyle.STRICT, null);
 825     }
 826 
 827     //-----------------------------------------------------------------------
 828     /**
 829      * The ISO time formatter that formats or parses a time with an
 830      * offset, such as '10:15+01:00' or '10:15:30+01:00'.
 831      * <p>
 832      * This returns an immutable formatter capable of formatting and parsing
 833      * the ISO-8601 extended offset time format.
 834      * The format consists of:
 835      * <ul>
 836      * <li>The {@link #ISO_LOCAL_TIME}
 837      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
 838      *  they will be handled even though this is not part of the ISO-8601 standard.
 839      *  Parsing is case insensitive.
 840      * </ul>
 841      * <p>
 842      * The returned formatter has no override chronology or zone.
 843      * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 844      */
 845     public static final DateTimeFormatter ISO_OFFSET_TIME;
 846     static {
 847         ISO_OFFSET_TIME = new DateTimeFormatterBuilder()
 848                 .parseCaseInsensitive()
 849                 .append(ISO_LOCAL_TIME)
 850                 .appendOffsetId()
 851                 .toFormatter(ResolverStyle.STRICT, null);
 852     }
 853 
 854     //-----------------------------------------------------------------------
 855     /**
 856      * The ISO time formatter that formats or parses a time, with the
 857      * offset if available, such as '10:15', '10:15:30' or '10:15:30+01:00'.
 858      * <p>
 859      * This returns an immutable formatter capable of formatting and parsing
 860      * the ISO-8601 extended offset time format.
 861      * The format consists of:
 862      * <ul>
 863      * <li>The {@link #ISO_LOCAL_TIME}
 864      * <li>If the offset is not available then the format is complete.
 865      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
 866      *  they will be handled even though this is not part of the ISO-8601 standard.
 867      *  Parsing is case insensitive.
 868      * </ul>
 869      * <p>
 870      * As this formatter has an optional element, it may be necessary to parse using
 871      * {@link DateTimeFormatter#parseBest}.
 872      * <p>
 873      * The returned formatter has no override chronology or zone.
 874      * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 875      */
 876     public static final DateTimeFormatter ISO_TIME;
 877     static {
 878         ISO_TIME = new DateTimeFormatterBuilder()
 879                 .parseCaseInsensitive()
 880                 .append(ISO_LOCAL_TIME)
 881                 .optionalStart()
 882                 .appendOffsetId()
 883                 .toFormatter(ResolverStyle.STRICT, null);
 884     }
 885 
 886     //-----------------------------------------------------------------------
 887     /**
 888      * The ISO date-time formatter that formats or parses a date-time without
 889      * an offset, such as '2011-12-03T10:15:30'.
 890      * <p>
 891      * This returns an immutable formatter capable of formatting and parsing
 892      * the ISO-8601 extended offset date-time format.
 893      * The format consists of:
 894      * <ul>
 895      * <li>The {@link #ISO_LOCAL_DATE}
 896      * <li>The letter 'T'. Parsing is case insensitive.
 897      * <li>The {@link #ISO_LOCAL_TIME}
 898      * </ul>
 899      * <p>
 900      * The returned formatter has a chronology of ISO set to ensure dates in
 901      * other calendar systems are correctly converted.
 902      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 903      */
 904     public static final DateTimeFormatter ISO_LOCAL_DATE_TIME;
 905     static {
 906         ISO_LOCAL_DATE_TIME = new DateTimeFormatterBuilder()
 907                 .parseCaseInsensitive()
 908                 .append(ISO_LOCAL_DATE)
 909                 .appendLiteral('T')
 910                 .append(ISO_LOCAL_TIME)
 911                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
 912     }
 913 
 914     //-----------------------------------------------------------------------
 915     /**
 916      * The ISO date-time formatter that formats or parses a date-time with an
 917      * offset, such as '2011-12-03T10:15:30+01:00'.
 918      * <p>
 919      * This returns an immutable formatter capable of formatting and parsing
 920      * the ISO-8601 extended offset date-time format.
 921      * The format consists of:
 922      * <ul>
 923      * <li>The {@link #ISO_LOCAL_DATE_TIME}
 924      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
 925      *  they will be handled even though this is not part of the ISO-8601 standard.
 926      *  The offset parsing is lenient, which allows the minutes and seconds to be optional.
 927      *  Parsing is case insensitive.
 928      * </ul>
 929      * <p>
 930      * The returned formatter has a chronology of ISO set to ensure dates in
 931      * other calendar systems are correctly converted.
 932      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 933      */
 934     public static final DateTimeFormatter ISO_OFFSET_DATE_TIME;
 935     static {
 936         ISO_OFFSET_DATE_TIME = new DateTimeFormatterBuilder()
 937                 .parseCaseInsensitive()
 938                 .append(ISO_LOCAL_DATE_TIME)
 939                 .parseLenient()
 940                 .appendOffsetId()
 941                 .parseStrict()
 942                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
 943     }
 944 
 945     //-----------------------------------------------------------------------
 946     /**
 947      * The ISO-like date-time formatter that formats or parses a date-time with
 948      * offset and zone, such as '2011-12-03T10:15:30+01:00[Europe/Paris]'.
 949      * <p>
 950      * This returns an immutable formatter capable of formatting and parsing
 951      * a format that extends the ISO-8601 extended offset date-time format
 952      * to add the time-zone.
 953      * The section in square brackets is not part of the ISO-8601 standard.
 954      * The format consists of:
 955      * <ul>
 956      * <li>The {@link #ISO_OFFSET_DATE_TIME}
 957      * <li>If the zone ID is not available or is a {@code ZoneOffset} then the format is complete.
 958      * <li>An open square bracket '['.
 959      * <li>The {@link ZoneId#getId() zone ID}. This is not part of the ISO-8601 standard.
 960      *  Parsing is case sensitive.
 961      * <li>A close square bracket ']'.
 962      * </ul>
 963      * <p>
 964      * The returned formatter has a chronology of ISO set to ensure dates in
 965      * other calendar systems are correctly converted.
 966      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 967      */
 968     public static final DateTimeFormatter ISO_ZONED_DATE_TIME;
 969     static {
 970         ISO_ZONED_DATE_TIME = new DateTimeFormatterBuilder()
 971                 .append(ISO_OFFSET_DATE_TIME)
 972                 .optionalStart()
 973                 .appendLiteral('[')
 974                 .parseCaseSensitive()
 975                 .appendZoneRegionId()
 976                 .appendLiteral(']')
 977                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
 978     }
 979 
 980     //-----------------------------------------------------------------------
 981     /**
 982      * The ISO-like date-time formatter that formats or parses a date-time with
 983      * the offset and zone if available, such as '2011-12-03T10:15:30',
 984      * '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'.
 985      * <p>
 986      * This returns an immutable formatter capable of formatting and parsing
 987      * the ISO-8601 extended local or offset date-time format, as well as the
 988      * extended non-ISO form specifying the time-zone.
 989      * The format consists of:
 990      * <ul>
 991      * <li>The {@link #ISO_LOCAL_DATE_TIME}
 992      * <li>If the offset is not available to format or parse then the format is complete.
 993      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
 994      *  they will be handled even though this is not part of the ISO-8601 standard.
 995      * <li>If the zone ID is not available or is a {@code ZoneOffset} then the format is complete.
 996      * <li>An open square bracket '['.
 997      * <li>The {@link ZoneId#getId() zone ID}. This is not part of the ISO-8601 standard.
 998      *  Parsing is case sensitive.
 999      * <li>A close square bracket ']'.
1000      * </ul>
1001      * <p>
1002      * As this formatter has an optional element, it may be necessary to parse using
1003      * {@link DateTimeFormatter#parseBest}.
1004      * <p>
1005      * The returned formatter has a chronology of ISO set to ensure dates in
1006      * other calendar systems are correctly converted.
1007      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1008      */
1009     public static final DateTimeFormatter ISO_DATE_TIME;
1010     static {
1011         ISO_DATE_TIME = new DateTimeFormatterBuilder()
1012                 .append(ISO_LOCAL_DATE_TIME)
1013                 .optionalStart()
1014                 .appendOffsetId()
1015                 .optionalStart()
1016                 .appendLiteral('[')
1017                 .parseCaseSensitive()
1018                 .appendZoneRegionId()
1019                 .appendLiteral(']')
1020                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1021     }
1022 
1023     //-----------------------------------------------------------------------
1024     /**
1025      * The ISO date formatter that formats or parses the ordinal date
1026      * without an offset, such as '2012-337'.
1027      * <p>
1028      * This returns an immutable formatter capable of formatting and parsing
1029      * the ISO-8601 extended ordinal date format.
1030      * The format consists of:
1031      * <ul>
1032      * <li>Four digits or more for the {@link ChronoField#YEAR year}.
1033      * Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits.
1034      * Years outside that range will have a prefixed positive or negative symbol.
1035      * <li>A dash
1036      * <li>Three digits for the {@link ChronoField#DAY_OF_YEAR day-of-year}.
1037      *  This is pre-padded by zero to ensure three digits.
1038      * <li>If the offset is not available to format or parse then the format is complete.
1039      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
1040      *  they will be handled even though this is not part of the ISO-8601 standard.
1041      *  Parsing is case insensitive.
1042      * </ul>
1043      * <p>
1044      * As this formatter has an optional element, it may be necessary to parse using
1045      * {@link DateTimeFormatter#parseBest}.
1046      * <p>
1047      * The returned formatter has a chronology of ISO set to ensure dates in
1048      * other calendar systems are correctly converted.
1049      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1050      */
1051     public static final DateTimeFormatter ISO_ORDINAL_DATE;
1052     static {
1053         ISO_ORDINAL_DATE = new DateTimeFormatterBuilder()
1054                 .parseCaseInsensitive()
1055                 .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
1056                 .appendLiteral('-')
1057                 .appendValue(DAY_OF_YEAR, 3)
1058                 .optionalStart()
1059                 .appendOffsetId()
1060                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1061     }
1062 
1063     //-----------------------------------------------------------------------
1064     /**
1065      * The ISO date formatter that formats or parses the week-based date
1066      * without an offset, such as '2012-W48-6'.
1067      * <p>
1068      * This returns an immutable formatter capable of formatting and parsing
1069      * the ISO-8601 extended week-based date format.
1070      * The format consists of:
1071      * <ul>
1072      * <li>Four digits or more for the {@link IsoFields#WEEK_BASED_YEAR week-based-year}.
1073      * Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits.
1074      * Years outside that range will have a prefixed positive or negative symbol.
1075      * <li>A dash
1076      * <li>The letter 'W'. Parsing is case insensitive.
1077      * <li>Two digits for the {@link IsoFields#WEEK_OF_WEEK_BASED_YEAR week-of-week-based-year}.
1078      *  This is pre-padded by zero to ensure three digits.
1079      * <li>A dash
1080      * <li>One digit for the {@link ChronoField#DAY_OF_WEEK day-of-week}.
1081      *  The value run from Monday (1) to Sunday (7).
1082      * <li>If the offset is not available to format or parse then the format is complete.
1083      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
1084      *  they will be handled even though this is not part of the ISO-8601 standard.
1085      *  Parsing is case insensitive.
1086      * </ul>
1087      * <p>
1088      * As this formatter has an optional element, it may be necessary to parse using
1089      * {@link DateTimeFormatter#parseBest}.
1090      * <p>
1091      * The returned formatter has a chronology of ISO set to ensure dates in
1092      * other calendar systems are correctly converted.
1093      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1094      */
1095     public static final DateTimeFormatter ISO_WEEK_DATE;
1096     static {
1097         ISO_WEEK_DATE = new DateTimeFormatterBuilder()
1098                 .parseCaseInsensitive()
1099                 .appendValue(IsoFields.WEEK_BASED_YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
1100                 .appendLiteral("-W")
1101                 .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2)
1102                 .appendLiteral('-')
1103                 .appendValue(DAY_OF_WEEK, 1)
1104                 .optionalStart()
1105                 .appendOffsetId()
1106                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1107     }
1108 
1109     //-----------------------------------------------------------------------
1110     /**
1111      * The ISO instant formatter that formats or parses an instant in UTC,
1112      * such as '2011-12-03T10:15:30Z'.
1113      * <p>
1114      * This returns an immutable formatter capable of formatting and parsing
1115      * the ISO-8601 instant format.
1116      * When formatting, the second-of-minute is always output.
1117      * The nano-of-second outputs zero, three, six or nine digits as necessary.
1118      * When parsing, time to at least the seconds field is required.
1119      * Fractional seconds from zero to nine are parsed.
1120      * The localized decimal style is not used.
1121      * <p>
1122      * This is a special case formatter intended to allow a human readable form
1123      * of an {@link java.time.Instant}. The {@code Instant} class is designed to
1124      * only represent a point in time and internally stores a value in nanoseconds
1125      * from a fixed epoch of 1970-01-01Z. As such, an {@code Instant} cannot be
1126      * formatted as a date or time without providing some form of time-zone.
1127      * This formatter allows the {@code Instant} to be formatted, by providing
1128      * a suitable conversion using {@code ZoneOffset.UTC}.
1129      * <p>
1130      * The format consists of:
1131      * <ul>
1132      * <li>The {@link #ISO_OFFSET_DATE_TIME} where the instant is converted from
1133      *  {@link ChronoField#INSTANT_SECONDS} and {@link ChronoField#NANO_OF_SECOND}
1134      *  using the {@code UTC} offset. Parsing is case insensitive.
1135      * </ul>
1136      * <p>
1137      * The returned formatter has no override chronology or zone.
1138      * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1139      */
1140     public static final DateTimeFormatter ISO_INSTANT;
1141     static {
1142         ISO_INSTANT = new DateTimeFormatterBuilder()
1143                 .parseCaseInsensitive()
1144                 .appendInstant()
1145                 .toFormatter(ResolverStyle.STRICT, null);
1146     }
1147 
1148     //-----------------------------------------------------------------------
1149     /**
1150      * The ISO date formatter that formats or parses a date without an
1151      * offset, such as '20111203'.
1152      * <p>
1153      * This returns an immutable formatter capable of formatting and parsing
1154      * the ISO-8601 basic local date format.
1155      * The format consists of:
1156      * <ul>
1157      * <li>Four digits for the {@link ChronoField#YEAR year}.
1158      *  Only years in the range 0000 to 9999 are supported.
1159      * <li>Two digits for the {@link ChronoField#MONTH_OF_YEAR month-of-year}.
1160      *  This is pre-padded by zero to ensure two digits.
1161      * <li>Two digits for the {@link ChronoField#DAY_OF_MONTH day-of-month}.
1162      *  This is pre-padded by zero to ensure two digits.
1163      * <li>If the offset is not available to format or parse then the format is complete.
1164      * <li>The {@link ZoneOffset#getId() offset ID} without colons. If the offset has
1165      *  seconds then they will be handled even though this is not part of the ISO-8601 standard.
1166      *  The offset parsing is lenient, which allows the minutes and seconds to be optional.
1167      *  Parsing is case insensitive.
1168      * </ul>
1169      * <p>
1170      * As this formatter has an optional element, it may be necessary to parse using
1171      * {@link DateTimeFormatter#parseBest}.
1172      * <p>
1173      * The returned formatter has a chronology of ISO set to ensure dates in
1174      * other calendar systems are correctly converted.
1175      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1176      */
1177     public static final DateTimeFormatter BASIC_ISO_DATE;
1178     static {
1179         BASIC_ISO_DATE = new DateTimeFormatterBuilder()
1180                 .parseCaseInsensitive()
1181                 .appendValue(YEAR, 4)
1182                 .appendValue(MONTH_OF_YEAR, 2)
1183                 .appendValue(DAY_OF_MONTH, 2)
1184                 .optionalStart()
1185                 .parseLenient()
1186                 .appendOffset("+HHMMss", "Z")
1187                 .parseStrict()
1188                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1189     }
1190 
1191     //-----------------------------------------------------------------------
1192     /**
1193      * The RFC-1123 date-time formatter, such as 'Tue, 3 Jun 2008 11:05:30 GMT'.
1194      * <p>
1195      * This returns an immutable formatter capable of formatting and parsing
1196      * most of the RFC-1123 format.
1197      * RFC-1123 updates RFC-822 changing the year from two digits to four.
1198      * This implementation requires a four digit year.
1199      * This implementation also does not handle North American or military zone
1200      * names, only 'GMT' and offset amounts.
1201      * <p>
1202      * The format consists of:
1203      * <ul>
1204      * <li>If the day-of-week is not available to format or parse then jump to day-of-month.
1205      * <li>Three letter {@link ChronoField#DAY_OF_WEEK day-of-week} in English.
1206      * <li>A comma
1207      * <li>A space
1208      * <li>One or two digits for the {@link ChronoField#DAY_OF_MONTH day-of-month}.
1209      * <li>A space
1210      * <li>Three letter {@link ChronoField#MONTH_OF_YEAR month-of-year} in English.
1211      * <li>A space
1212      * <li>Four digits for the {@link ChronoField#YEAR year}.
1213      *  Only years in the range 0000 to 9999 are supported.
1214      * <li>A space
1215      * <li>Two digits for the {@link ChronoField#HOUR_OF_DAY hour-of-day}.
1216      *  This is pre-padded by zero to ensure two digits.
1217      * <li>A colon
1218      * <li>Two digits for the {@link ChronoField#MINUTE_OF_HOUR minute-of-hour}.
1219      *  This is pre-padded by zero to ensure two digits.
1220      * <li>If the second-of-minute is not available then jump to the next space.
1221      * <li>A colon
1222      * <li>Two digits for the {@link ChronoField#SECOND_OF_MINUTE second-of-minute}.
1223      *  This is pre-padded by zero to ensure two digits.
1224      * <li>A space
1225      * <li>The {@link ZoneOffset#getId() offset ID} without colons or seconds.
1226      *  An offset of zero uses "GMT". North American zone names and military zone names are not handled.
1227      * </ul>
1228      * <p>
1229      * Parsing is case insensitive.
1230      * <p>
1231      * The returned formatter has a chronology of ISO set to ensure dates in
1232      * other calendar systems are correctly converted.
1233      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
1234      */
1235     public static final DateTimeFormatter RFC_1123_DATE_TIME;
1236     static {
1237         // manually code maps to ensure correct data always used
1238         // (locale data can be changed by application code)
1239         Map<Long, String> dow = new HashMap<>();
1240         dow.put(1L, "Mon");
1241         dow.put(2L, "Tue");
1242         dow.put(3L, "Wed");
1243         dow.put(4L, "Thu");
1244         dow.put(5L, "Fri");
1245         dow.put(6L, "Sat");
1246         dow.put(7L, "Sun");
1247         Map<Long, String> moy = new HashMap<>();
1248         moy.put(1L, "Jan");
1249         moy.put(2L, "Feb");
1250         moy.put(3L, "Mar");
1251         moy.put(4L, "Apr");
1252         moy.put(5L, "May");
1253         moy.put(6L, "Jun");
1254         moy.put(7L, "Jul");
1255         moy.put(8L, "Aug");
1256         moy.put(9L, "Sep");
1257         moy.put(10L, "Oct");
1258         moy.put(11L, "Nov");
1259         moy.put(12L, "Dec");
1260         RFC_1123_DATE_TIME = new DateTimeFormatterBuilder()
1261                 .parseCaseInsensitive()
1262                 .parseLenient()
1263                 .optionalStart()
1264                 .appendText(DAY_OF_WEEK, dow)
1265                 .appendLiteral(", ")
1266                 .optionalEnd()
1267                 .appendValue(DAY_OF_MONTH, 1, 2, SignStyle.NOT_NEGATIVE)
1268                 .appendLiteral(' ')
1269                 .appendText(MONTH_OF_YEAR, moy)
1270                 .appendLiteral(' ')
1271                 .appendValue(YEAR, 4)  // 2 digit year not handled
1272                 .appendLiteral(' ')
1273                 .appendValue(HOUR_OF_DAY, 2)
1274                 .appendLiteral(':')
1275                 .appendValue(MINUTE_OF_HOUR, 2)
1276                 .optionalStart()
1277                 .appendLiteral(':')
1278                 .appendValue(SECOND_OF_MINUTE, 2)
1279                 .optionalEnd()
1280                 .appendLiteral(' ')
1281                 .appendOffset("+HHMM", "GMT")  // should handle UT/Z/EST/EDT/CST/CDT/MST/MDT/PST/MDT
1282                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
1283     }
1284 
1285     //-----------------------------------------------------------------------
1286     /**
1287      * A query that provides access to the excess days that were parsed.
1288      * <p>
1289      * This returns a singleton {@linkplain TemporalQuery query} that provides
1290      * access to additional information from the parse. The query always returns
1291      * a non-null period, with a zero period returned instead of null.
1292      * <p>
1293      * There are two situations where this query may return a non-zero period.
1294      * <ul>
1295      * <li>If the {@code ResolverStyle} is {@code LENIENT} and a time is parsed
1296      *  without a date, then the complete result of the parse consists of a
1297      *  {@code LocalTime} and an excess {@code Period} in days.
1298      *
1299      * <li>If the {@code ResolverStyle} is {@code SMART} and a time is parsed
1300      *  without a date where the time is 24:00:00, then the complete result of
1301      *  the parse consists of a {@code LocalTime} of 00:00:00 and an excess
1302      *  {@code Period} of one day.
1303      * </ul>
1304      * <p>
1305      * In both cases, if a complete {@code ChronoLocalDateTime} or {@code Instant}
1306      * is parsed, then the excess days are added to the date part.
1307      * As a result, this query will return a zero period.
1308      * <p>
1309      * The {@code SMART} behaviour handles the common "end of day" 24:00 value.
1310      * Processing in {@code LENIENT} mode also produces the same result:
1311      * <pre>
1312      *  Text to parse        Parsed object                         Excess days
1313      *  "2012-12-03T00:00"   LocalDateTime.of(2012, 12, 3, 0, 0)   ZERO
1314      *  "2012-12-03T24:00"   LocalDateTime.of(2012, 12, 4, 0, 0)   ZERO
1315      *  "00:00"              LocalTime.of(0, 0)                    ZERO
1316      *  "24:00"              LocalTime.of(0, 0)                    Period.ofDays(1)
1317      * </pre>
1318      * The query can be used as follows:
1319      * <pre>
1320      *  TemporalAccessor parsed = formatter.parse(str);
1321      *  LocalTime time = parsed.query(LocalTime::from);
1322      *  Period extraDays = parsed.query(DateTimeFormatter.parsedExcessDays());
1323      * </pre>
1324      * @return a query that provides access to the excess days that were parsed
1325      */
1326     public static final TemporalQuery<Period> parsedExcessDays() {
1327         return PARSED_EXCESS_DAYS;
1328     }
1329     private static final TemporalQuery<Period> PARSED_EXCESS_DAYS = t -> {
1330         if (t instanceof Parsed) {
1331             return ((Parsed) t).excessDays;
1332         } else {
1333             return Period.ZERO;
1334         }
1335     };
1336 
1337     /**
1338      * A query that provides access to whether a leap-second was parsed.
1339      * <p>
1340      * This returns a singleton {@linkplain TemporalQuery query} that provides
1341      * access to additional information from the parse. The query always returns
1342      * a non-null boolean, true if parsing saw a leap-second, false if not.
1343      * <p>
1344      * Instant parsing handles the special "leap second" time of '23:59:60'.
1345      * Leap seconds occur at '23:59:60' in the UTC time-zone, but at other
1346      * local times in different time-zones. To avoid this potential ambiguity,
1347      * the handling of leap-seconds is limited to
1348      * {@link DateTimeFormatterBuilder#appendInstant()}, as that method
1349      * always parses the instant with the UTC zone offset.
1350      * <p>
1351      * If the time '23:59:60' is received, then a simple conversion is applied,
1352      * replacing the second-of-minute of 60 with 59. This query can be used
1353      * on the parse result to determine if the leap-second adjustment was made.
1354      * The query will return {@code true} if it did adjust to remove the
1355      * leap-second, and {@code false} if not. Note that applying a leap-second
1356      * smoothing mechanism, such as UTC-SLS, is the responsibility of the
1357      * application, as follows:
1358      * <pre>
1359      *  TemporalAccessor parsed = formatter.parse(str);
1360      *  Instant instant = parsed.query(Instant::from);
1361      *  if (parsed.query(DateTimeFormatter.parsedLeapSecond())) {
1362      *    // validate leap-second is correct and apply correct smoothing
1363      *  }
1364      * </pre>
1365      * @return a query that provides access to whether a leap-second was parsed
1366      */
1367     public static final TemporalQuery<Boolean> parsedLeapSecond() {
1368         return PARSED_LEAP_SECOND;
1369     }
1370     private static final TemporalQuery<Boolean> PARSED_LEAP_SECOND = t -> {
1371         if (t instanceof Parsed) {
1372             return ((Parsed) t).leapSecond;
1373         } else {
1374             return Boolean.FALSE;
1375         }
1376     };
1377 
1378     //-----------------------------------------------------------------------
1379     /**
1380      * Constructor.
1381      *
1382      * @param printerParser  the printer/parser to use, not null
1383      * @param locale  the locale to use, not null
1384      * @param decimalStyle  the DecimalStyle to use, not null
1385      * @param resolverStyle  the resolver style to use, not null
1386      * @param resolverFields  the fields to use during resolving, null for all fields
1387      * @param chrono  the chronology to use, null for no override
1388      * @param zone  the zone to use, null for no override
1389      */
1390     DateTimeFormatter(CompositePrinterParser printerParser,
1391             Locale locale, DecimalStyle decimalStyle,
1392             ResolverStyle resolverStyle, Set<TemporalField> resolverFields,
1393             Chronology chrono, ZoneId zone) {
1394         this.printerParser = Objects.requireNonNull(printerParser, "printerParser");
1395         this.resolverFields = resolverFields;
1396         this.locale = Objects.requireNonNull(locale, "locale");
1397         this.decimalStyle = Objects.requireNonNull(decimalStyle, "decimalStyle");
1398         this.resolverStyle = Objects.requireNonNull(resolverStyle, "resolverStyle");
1399         this.chrono = chrono;
1400         this.zone = zone;
1401     }
1402 
1403     //-----------------------------------------------------------------------
1404     /**
1405      * Gets the locale to be used during formatting.
1406      * <p>
1407      * This is used to lookup any part of the formatter needing specific
1408      * localization, such as the text or localized pattern.
1409      *
1410      * @return the locale of this formatter, not null
1411      */
1412     public Locale getLocale() {
1413         return locale;
1414     }
1415 
1416     /**
1417      * Returns a copy of this formatter with a new locale.
1418      * <p>
1419      * This is used to lookup any part of the formatter needing specific
1420      * localization, such as the text or localized pattern.
1421      * <p>
1422      * This instance is immutable and unaffected by this method call.
1423      *
1424      * @param locale  the new locale, not null
1425      * @return a formatter based on this formatter with the requested locale, not null
1426      */
1427     public DateTimeFormatter withLocale(Locale locale) {
1428         if (this.locale.equals(locale)) {
1429             return this;
1430         }
1431         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1432     }
1433 
1434     //-----------------------------------------------------------------------
1435     /**
1436      * Gets the DecimalStyle to be used during formatting.
1437      *
1438      * @return the locale of this formatter, not null
1439      */
1440     public DecimalStyle getDecimalStyle() {
1441         return decimalStyle;
1442     }
1443 
1444     /**
1445      * Returns a copy of this formatter with a new DecimalStyle.
1446      * <p>
1447      * This instance is immutable and unaffected by this method call.
1448      *
1449      * @param decimalStyle  the new DecimalStyle, not null
1450      * @return a formatter based on this formatter with the requested DecimalStyle, not null
1451      */
1452     public DateTimeFormatter withDecimalStyle(DecimalStyle decimalStyle) {
1453         if (this.decimalStyle.equals(decimalStyle)) {
1454             return this;
1455         }
1456         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1457     }
1458 
1459     //-----------------------------------------------------------------------
1460     /**
1461      * Gets the overriding chronology to be used during formatting.
1462      * <p>
1463      * This returns the override chronology, used to convert dates.
1464      * By default, a formatter has no override chronology, returning null.
1465      * See {@link #withChronology(Chronology)} for more details on overriding.
1466      *
1467      * @return the override chronology of this formatter, null if no override
1468      */
1469     public Chronology getChronology() {
1470         return chrono;
1471     }
1472 
1473     /**
1474      * Returns a copy of this formatter with a new override chronology.
1475      * <p>
1476      * This returns a formatter with similar state to this formatter but
1477      * with the override chronology set.
1478      * By default, a formatter has no override chronology, returning null.
1479      * <p>
1480      * If an override is added, then any date that is formatted or parsed will be affected.
1481      * <p>
1482      * When formatting, if the temporal object contains a date, then it will
1483      * be converted to a date in the override chronology.
1484      * Whether the temporal contains a date is determined by querying the
1485      * {@link ChronoField#EPOCH_DAY EPOCH_DAY} field.
1486      * Any time or zone will be retained unaltered unless overridden.
1487      * <p>
1488      * If the temporal object does not contain a date, but does contain one
1489      * or more {@code ChronoField} date fields, then a {@code DateTimeException}
1490      * is thrown. In all other cases, the override chronology is added to the temporal,
1491      * replacing any previous chronology, but without changing the date/time.
1492      * <p>
1493      * When parsing, there are two distinct cases to consider.
1494      * If a chronology has been parsed directly from the text, perhaps because
1495      * {@link DateTimeFormatterBuilder#appendChronologyId()} was used, then
1496      * this override chronology has no effect.
1497      * If no zone has been parsed, then this override chronology will be used
1498      * to interpret the {@code ChronoField} values into a date according to the
1499      * date resolving rules of the chronology.
1500      * <p>
1501      * This instance is immutable and unaffected by this method call.
1502      *
1503      * @param chrono  the new chronology, null if no override
1504      * @return a formatter based on this formatter with the requested override chronology, not null
1505      */
1506     public DateTimeFormatter withChronology(Chronology chrono) {
1507         if (Objects.equals(this.chrono, chrono)) {
1508             return this;
1509         }
1510         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1511     }
1512 
1513     //-----------------------------------------------------------------------
1514     /**
1515      * Gets the overriding zone to be used during formatting.
1516      * <p>
1517      * This returns the override zone, used to convert instants.
1518      * By default, a formatter has no override zone, returning null.
1519      * See {@link #withZone(ZoneId)} for more details on overriding.
1520      *
1521      * @return the override zone of this formatter, null if no override
1522      */
1523     public ZoneId getZone() {
1524         return zone;
1525     }
1526 
1527     /**
1528      * Returns a copy of this formatter with a new override zone.
1529      * <p>
1530      * This returns a formatter with similar state to this formatter but
1531      * with the override zone set.
1532      * By default, a formatter has no override zone, returning null.
1533      * <p>
1534      * If an override is added, then any instant that is formatted or parsed will be affected.
1535      * <p>
1536      * When formatting, if the temporal object contains an instant, then it will
1537      * be converted to a zoned date-time using the override zone.
1538      * Whether the temporal is an instant is determined by querying the
1539      * {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS} field.
1540      * If the input has a chronology then it will be retained unless overridden.
1541      * If the input does not have a chronology, such as {@code Instant}, then
1542      * the ISO chronology will be used.
1543      * <p>
1544      * If the temporal object does not contain an instant, but does contain
1545      * an offset then an additional check is made. If the normalized override
1546      * zone is an offset that differs from the offset of the temporal, then
1547      * a {@code DateTimeException} is thrown. In all other cases, the override
1548      * zone is added to the temporal, replacing any previous zone, but without
1549      * changing the date/time.
1550      * <p>
1551      * When parsing, there are two distinct cases to consider.
1552      * If a zone has been parsed directly from the text, perhaps because
1553      * {@link DateTimeFormatterBuilder#appendZoneId()} was used, then
1554      * this override zone has no effect.
1555      * If no zone has been parsed, then this override zone will be included in
1556      * the result of the parse where it can be used to build instants and date-times.
1557      * <p>
1558      * This instance is immutable and unaffected by this method call.
1559      *
1560      * @param zone  the new override zone, null if no override
1561      * @return a formatter based on this formatter with the requested override zone, not null
1562      */
1563     public DateTimeFormatter withZone(ZoneId zone) {
1564         if (Objects.equals(this.zone, zone)) {
1565             return this;
1566         }
1567         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1568     }
1569 
1570     //-----------------------------------------------------------------------
1571     /**
1572      * Gets the resolver style to use during parsing.
1573      * <p>
1574      * This returns the resolver style, used during the second phase of parsing
1575      * when fields are resolved into dates and times.
1576      * By default, a formatter has the {@link ResolverStyle#SMART SMART} resolver style.
1577      * See {@link #withResolverStyle(ResolverStyle)} for more details.
1578      *
1579      * @return the resolver style of this formatter, not null
1580      */
1581     public ResolverStyle getResolverStyle() {
1582         return resolverStyle;
1583     }
1584 
1585     /**
1586      * Returns a copy of this formatter with a new resolver style.
1587      * <p>
1588      * This returns a formatter with similar state to this formatter but
1589      * with the resolver style set. By default, a formatter has the
1590      * {@link ResolverStyle#SMART SMART} resolver style.
1591      * <p>
1592      * Changing the resolver style only has an effect during parsing.
1593      * Parsing a text string occurs in two phases.
1594      * Phase 1 is a basic text parse according to the fields added to the builder.
1595      * Phase 2 resolves the parsed field-value pairs into date and/or time objects.
1596      * The resolver style is used to control how phase 2, resolving, happens.
1597      * See {@code ResolverStyle} for more information on the options available.
1598      * <p>
1599      * This instance is immutable and unaffected by this method call.
1600      *
1601      * @param resolverStyle  the new resolver style, not null
1602      * @return a formatter based on this formatter with the requested resolver style, not null
1603      */
1604     public DateTimeFormatter withResolverStyle(ResolverStyle resolverStyle) {
1605         Objects.requireNonNull(resolverStyle, "resolverStyle");
1606         if (Objects.equals(this.resolverStyle, resolverStyle)) {
1607             return this;
1608         }
1609         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1610     }
1611 
1612     //-----------------------------------------------------------------------
1613     /**
1614      * Gets the resolver fields to use during parsing.
1615      * <p>
1616      * This returns the resolver fields, used during the second phase of parsing
1617      * when fields are resolved into dates and times.
1618      * By default, a formatter has no resolver fields, and thus returns null.
1619      * See {@link #withResolverFields(Set)} for more details.
1620      *
1621      * @return the immutable set of resolver fields of this formatter, null if no fields
1622      */
1623     public Set<TemporalField> getResolverFields() {
1624         return resolverFields;
1625     }
1626 
1627     /**
1628      * Returns a copy of this formatter with a new set of resolver fields.
1629      * <p>
1630      * This returns a formatter with similar state to this formatter but with
1631      * the resolver fields set. By default, a formatter has no resolver fields.
1632      * <p>
1633      * Changing the resolver fields only has an effect during parsing.
1634      * Parsing a text string occurs in two phases.
1635      * Phase 1 is a basic text parse according to the fields added to the builder.
1636      * Phase 2 resolves the parsed field-value pairs into date and/or time objects.
1637      * The resolver fields are used to filter the field-value pairs between phase 1 and 2.
1638      * <p>
1639      * This can be used to select between two or more ways that a date or time might
1640      * be resolved. For example, if the formatter consists of year, month, day-of-month
1641      * and day-of-year, then there are two ways to resolve a date.
1642      * Calling this method with the arguments {@link ChronoField#YEAR YEAR} and
1643      * {@link ChronoField#DAY_OF_YEAR DAY_OF_YEAR} will ensure that the date is
1644      * resolved using the year and day-of-year, effectively meaning that the month
1645      * and day-of-month are ignored during the resolving phase.
1646      * <p>
1647      * In a similar manner, this method can be used to ignore secondary fields that
1648      * would otherwise be cross-checked. For example, if the formatter consists of year,
1649      * month, day-of-month and day-of-week, then there is only one way to resolve a
1650      * date, but the parsed value for day-of-week will be cross-checked against the
1651      * resolved date. Calling this method with the arguments {@link ChronoField#YEAR YEAR},
1652      * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and
1653      * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} will ensure that the date is
1654      * resolved correctly, but without any cross-check for the day-of-week.
1655      * <p>
1656      * In implementation terms, this method behaves as follows. The result of the
1657      * parsing phase can be considered to be a map of field to value. The behavior
1658      * of this method is to cause that map to be filtered between phase 1 and 2,
1659      * removing all fields other than those specified as arguments to this method.
1660      * <p>
1661      * This instance is immutable and unaffected by this method call.
1662      *
1663      * @param resolverFields  the new set of resolver fields, null if no fields
1664      * @return a formatter based on this formatter with the requested resolver style, not null
1665      */
1666     public DateTimeFormatter withResolverFields(TemporalField... resolverFields) {
1667         Set<TemporalField> fields = null;
1668         if (resolverFields != null) {
1669             fields = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(resolverFields)));
1670         }
1671         if (Objects.equals(this.resolverFields, fields)) {
1672             return this;
1673         }
1674         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, fields, chrono, zone);
1675     }
1676 
1677     /**
1678      * Returns a copy of this formatter with a new set of resolver fields.
1679      * <p>
1680      * This returns a formatter with similar state to this formatter but with
1681      * the resolver fields set. By default, a formatter has no resolver fields.
1682      * <p>
1683      * Changing the resolver fields only has an effect during parsing.
1684      * Parsing a text string occurs in two phases.
1685      * Phase 1 is a basic text parse according to the fields added to the builder.
1686      * Phase 2 resolves the parsed field-value pairs into date and/or time objects.
1687      * The resolver fields are used to filter the field-value pairs between phase 1 and 2.
1688      * <p>
1689      * This can be used to select between two or more ways that a date or time might
1690      * be resolved. For example, if the formatter consists of year, month, day-of-month
1691      * and day-of-year, then there are two ways to resolve a date.
1692      * Calling this method with the arguments {@link ChronoField#YEAR YEAR} and
1693      * {@link ChronoField#DAY_OF_YEAR DAY_OF_YEAR} will ensure that the date is
1694      * resolved using the year and day-of-year, effectively meaning that the month
1695      * and day-of-month are ignored during the resolving phase.
1696      * <p>
1697      * In a similar manner, this method can be used to ignore secondary fields that
1698      * would otherwise be cross-checked. For example, if the formatter consists of year,
1699      * month, day-of-month and day-of-week, then there is only one way to resolve a
1700      * date, but the parsed value for day-of-week will be cross-checked against the
1701      * resolved date. Calling this method with the arguments {@link ChronoField#YEAR YEAR},
1702      * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and
1703      * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} will ensure that the date is
1704      * resolved correctly, but without any cross-check for the day-of-week.
1705      * <p>
1706      * In implementation terms, this method behaves as follows. The result of the
1707      * parsing phase can be considered to be a map of field to value. The behavior
1708      * of this method is to cause that map to be filtered between phase 1 and 2,
1709      * removing all fields other than those specified as arguments to this method.
1710      * <p>
1711      * This instance is immutable and unaffected by this method call.
1712      *
1713      * @param resolverFields  the new set of resolver fields, null if no fields
1714      * @return a formatter based on this formatter with the requested resolver style, not null
1715      */
1716     public DateTimeFormatter withResolverFields(Set<TemporalField> resolverFields) {
1717         if (Objects.equals(this.resolverFields, resolverFields)) {
1718             return this;
1719         }
1720         if (resolverFields != null) {
1721             resolverFields = Collections.unmodifiableSet(new HashSet<>(resolverFields));
1722         }
1723         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1724     }
1725 
1726     //-----------------------------------------------------------------------
1727     /**
1728      * Formats a date-time object using this formatter.
1729      * <p>
1730      * This formats the date-time to a String using the rules of the formatter.
1731      *
1732      * @param temporal  the temporal object to format, not null
1733      * @return the formatted string, not null
1734      * @throws DateTimeException if an error occurs during formatting
1735      */
1736     public String format(TemporalAccessor temporal) {
1737         StringBuilder buf = new StringBuilder(32);
1738         formatTo(temporal, buf);
1739         return buf.toString();
1740     }
1741 
1742     //-----------------------------------------------------------------------
1743     /**
1744      * Formats a date-time object to an {@code Appendable} using this formatter.
1745      * <p>
1746      * This outputs the formatted date-time to the specified destination.
1747      * {@link Appendable} is a general purpose interface that is implemented by all
1748      * key character output classes including {@code StringBuffer}, {@code StringBuilder},
1749      * {@code PrintStream} and {@code Writer}.
1750      * <p>
1751      * Although {@code Appendable} methods throw an {@code IOException}, this method does not.
1752      * Instead, any {@code IOException} is wrapped in a runtime exception.
1753      *
1754      * @param temporal  the temporal object to format, not null
1755      * @param appendable  the appendable to format to, not null
1756      * @throws DateTimeException if an error occurs during formatting
1757      */
1758     public void formatTo(TemporalAccessor temporal, Appendable appendable) {
1759         Objects.requireNonNull(temporal, "temporal");
1760         Objects.requireNonNull(appendable, "appendable");
1761         try {
1762             DateTimePrintContext context = new DateTimePrintContext(temporal, this);
1763             if (appendable instanceof StringBuilder) {
1764                 printerParser.format(context, (StringBuilder) appendable);
1765             } else {
1766                 // buffer output to avoid writing to appendable in case of error
1767                 StringBuilder buf = new StringBuilder(32);
1768                 printerParser.format(context, buf);
1769                 appendable.append(buf);
1770             }
1771         } catch (IOException ex) {
1772             throw new DateTimeException(ex.getMessage(), ex);
1773         }
1774     }
1775 
1776     //-----------------------------------------------------------------------
1777     /**
1778      * Fully parses the text producing a temporal object.
1779      * <p>
1780      * This parses the entire text producing a temporal object.
1781      * It is typically more useful to use {@link #parse(CharSequence, TemporalQuery)}.
1782      * The result of this method is {@code TemporalAccessor} which has been resolved,
1783      * applying basic validation checks to help ensure a valid date-time.
1784      * <p>
1785      * If the parse completes without reading the entire length of the text,
1786      * or a problem occurs during parsing or merging, then an exception is thrown.
1787      *
1788      * @param text  the text to parse, not null
1789      * @return the parsed temporal object, not null
1790      * @throws DateTimeParseException if unable to parse the requested result
1791      */
1792     public TemporalAccessor parse(CharSequence text) {
1793         Objects.requireNonNull(text, "text");
1794         try {
1795             return parseResolved0(text, null);
1796         } catch (DateTimeParseException ex) {
1797             throw ex;
1798         } catch (RuntimeException ex) {
1799             throw createError(text, ex);
1800         }
1801     }
1802 
1803     /**
1804      * Parses the text using this formatter, providing control over the text position.
1805      * <p>
1806      * This parses the text without requiring the parse to start from the beginning
1807      * of the string or finish at the end.
1808      * The result of this method is {@code TemporalAccessor} which has been resolved,
1809      * applying basic validation checks to help ensure a valid date-time.
1810      * <p>
1811      * The text will be parsed from the specified start {@code ParsePosition}.
1812      * The entire length of the text does not have to be parsed, the {@code ParsePosition}
1813      * will be updated with the index at the end of parsing.
1814      * <p>
1815      * The operation of this method is slightly different to similar methods using
1816      * {@code ParsePosition} on {@code java.text.Format}. That class will return
1817      * errors using the error index on the {@code ParsePosition}. By contrast, this
1818      * method will throw a {@link DateTimeParseException} if an error occurs, with
1819      * the exception containing the error index.
1820      * This change in behavior is necessary due to the increased complexity of
1821      * parsing and resolving dates/times in this API.
1822      * <p>
1823      * If the formatter parses the same field more than once with different values,
1824      * the result will be an error.
1825      *
1826      * @param text  the text to parse, not null
1827      * @param position  the position to parse from, updated with length parsed
1828      *  and the index of any error, not null
1829      * @return the parsed temporal object, not null
1830      * @throws DateTimeParseException if unable to parse the requested result
1831      * @throws IndexOutOfBoundsException if the position is invalid
1832      */
1833     public TemporalAccessor parse(CharSequence text, ParsePosition position) {
1834         Objects.requireNonNull(text, "text");
1835         Objects.requireNonNull(position, "position");
1836         try {
1837             return parseResolved0(text, position);
1838         } catch (DateTimeParseException | IndexOutOfBoundsException ex) {
1839             throw ex;
1840         } catch (RuntimeException ex) {
1841             throw createError(text, ex);
1842         }
1843     }
1844 
1845     //-----------------------------------------------------------------------
1846     /**
1847      * Fully parses the text producing an object of the specified type.
1848      * <p>
1849      * Most applications should use this method for parsing.
1850      * It parses the entire text to produce the required date-time.
1851      * The query is typically a method reference to a {@code from(TemporalAccessor)} method.
1852      * For example:
1853      * <pre>
1854      *  LocalDateTime dt = parser.parse(str, LocalDateTime::from);
1855      * </pre>
1856      * If the parse completes without reading the entire length of the text,
1857      * or a problem occurs during parsing or merging, then an exception is thrown.
1858      *
1859      * @param <T> the type of the parsed date-time
1860      * @param text  the text to parse, not null
1861      * @param query  the query defining the type to parse to, not null
1862      * @return the parsed date-time, not null
1863      * @throws DateTimeParseException if unable to parse the requested result
1864      */
1865     public <T> T parse(CharSequence text, TemporalQuery<T> query) {
1866         Objects.requireNonNull(text, "text");
1867         Objects.requireNonNull(query, "query");
1868         try {
1869             return parseResolved0(text, null).query(query);
1870         } catch (DateTimeParseException ex) {
1871             throw ex;
1872         } catch (RuntimeException ex) {
1873             throw createError(text, ex);
1874         }
1875     }
1876 
1877     /**
1878      * Fully parses the text producing an object of one of the specified types.
1879      * <p>
1880      * This parse method is convenient for use when the parser can handle optional elements.
1881      * For example, a pattern of 'uuuu-MM-dd HH.mm[ VV]' can be fully parsed to a {@code ZonedDateTime},
1882      * or partially parsed to a {@code LocalDateTime}.
1883      * The queries must be specified in order, starting from the best matching full-parse option
1884      * and ending with the worst matching minimal parse option.
1885      * The query is typically a method reference to a {@code from(TemporalAccessor)} method.
1886      * <p>
1887      * The result is associated with the first type that successfully parses.
1888      * Normally, applications will use {@code instanceof} to check the result.
1889      * For example:
1890      * <pre>
1891      *  TemporalAccessor dt = parser.parseBest(str, ZonedDateTime::from, LocalDateTime::from);
1892      *  if (dt instanceof ZonedDateTime) {
1893      *   ...
1894      *  } else {
1895      *   ...
1896      *  }
1897      * </pre>
1898      * If the parse completes without reading the entire length of the text,
1899      * or a problem occurs during parsing or merging, then an exception is thrown.
1900      *
1901      * @param text  the text to parse, not null
1902      * @param queries  the queries defining the types to attempt to parse to,
1903      *  must implement {@code TemporalAccessor}, not null
1904      * @return the parsed date-time, not null
1905      * @throws IllegalArgumentException if less than 2 types are specified
1906      * @throws DateTimeParseException if unable to parse the requested result
1907      */
1908     public TemporalAccessor parseBest(CharSequence text, TemporalQuery<?>... queries) {
1909         Objects.requireNonNull(text, "text");
1910         Objects.requireNonNull(queries, "queries");
1911         if (queries.length < 2) {
1912             throw new IllegalArgumentException("At least two queries must be specified");
1913         }
1914         try {
1915             TemporalAccessor resolved = parseResolved0(text, null);
1916             for (TemporalQuery<?> query : queries) {
1917                 try {
1918                     return (TemporalAccessor) resolved.query(query);
1919                 } catch (RuntimeException ex) {
1920                     // continue
1921                 }
1922             }
1923             throw new DateTimeException("Unable to convert parsed text using any of the specified queries");
1924         } catch (DateTimeParseException ex) {
1925             throw ex;
1926         } catch (RuntimeException ex) {
1927             throw createError(text, ex);
1928         }
1929     }
1930 
1931     private DateTimeParseException createError(CharSequence text, RuntimeException ex) {
1932         String abbr;
1933         if (text.length() > 64) {
1934             abbr = text.subSequence(0, 64).toString() + "...";
1935         } else {
1936             abbr = text.toString();
1937         }
1938         return new DateTimeParseException("Text '" + abbr + "' could not be parsed: " + ex.getMessage(), text, 0, ex);
1939     }
1940 
1941     //-----------------------------------------------------------------------
1942     /**
1943      * Parses and resolves the specified text.
1944      * <p>
1945      * This parses to a {@code TemporalAccessor} ensuring that the text is fully parsed.
1946      *
1947      * @param text  the text to parse, not null
1948      * @param position  the position to parse from, updated with length parsed
1949      *  and the index of any error, null if parsing whole string
1950      * @return the resolved result of the parse, not null
1951      * @throws DateTimeParseException if the parse fails
1952      * @throws DateTimeException if an error occurs while resolving the date or time
1953      * @throws IndexOutOfBoundsException if the position is invalid
1954      */
1955     private TemporalAccessor parseResolved0(final CharSequence text, final ParsePosition position) {
1956         ParsePosition pos = (position != null ? position : new ParsePosition(0));
1957         DateTimeParseContext context = parseUnresolved0(text, pos);
1958         if (context == null || pos.getErrorIndex() >= 0 || (position == null && pos.getIndex() < text.length())) {
1959             String abbr;
1960             if (text.length() > 64) {
1961                 abbr = text.subSequence(0, 64).toString() + "...";
1962             } else {
1963                 abbr = text.toString();
1964             }
1965             if (pos.getErrorIndex() >= 0) {
1966                 throw new DateTimeParseException("Text '" + abbr + "' could not be parsed at index " +
1967                         pos.getErrorIndex(), text, pos.getErrorIndex());
1968             } else {
1969                 throw new DateTimeParseException("Text '" + abbr + "' could not be parsed, unparsed text found at index " +
1970                         pos.getIndex(), text, pos.getIndex());
1971             }
1972         }
1973         return context.toResolved(resolverStyle, resolverFields);
1974     }
1975 
1976     /**
1977      * Parses the text using this formatter, without resolving the result, intended
1978      * for advanced use cases.
1979      * <p>
1980      * Parsing is implemented as a two-phase operation.
1981      * First, the text is parsed using the layout defined by the formatter, producing
1982      * a {@code Map} of field to value, a {@code ZoneId} and a {@code Chronology}.
1983      * Second, the parsed data is <em>resolved</em>, by validating, combining and
1984      * simplifying the various fields into more useful ones.
1985      * This method performs the parsing stage but not the resolving stage.
1986      * <p>
1987      * The result of this method is {@code TemporalAccessor} which represents the
1988      * data as seen in the input. Values are not validated, thus parsing a date string
1989      * of '2012-00-65' would result in a temporal with three fields - year of '2012',
1990      * month of '0' and day-of-month of '65'.
1991      * <p>
1992      * The text will be parsed from the specified start {@code ParsePosition}.
1993      * The entire length of the text does not have to be parsed, the {@code ParsePosition}
1994      * will be updated with the index at the end of parsing.
1995      * <p>
1996      * Errors are returned using the error index field of the {@code ParsePosition}
1997      * instead of {@code DateTimeParseException}.
1998      * The returned error index will be set to an index indicative of the error.
1999      * Callers must check for errors before using the result.
2000      * <p>
2001      * If the formatter parses the same field more than once with different values,
2002      * the result will be an error.
2003      * <p>
2004      * This method is intended for advanced use cases that need access to the
2005      * internal state during parsing. Typical application code should use
2006      * {@link #parse(CharSequence, TemporalQuery)} or the parse method on the target type.
2007      *
2008      * @param text  the text to parse, not null
2009      * @param position  the position to parse from, updated with length parsed
2010      *  and the index of any error, not null
2011      * @return the parsed text, null if the parse results in an error
2012      * @throws DateTimeException if some problem occurs during parsing
2013      * @throws IndexOutOfBoundsException if the position is invalid
2014      */
2015     public TemporalAccessor parseUnresolved(CharSequence text, ParsePosition position) {
2016         DateTimeParseContext context = parseUnresolved0(text, position);
2017         if (context == null) {
2018             return null;
2019         }
2020         return context.toUnresolved();
2021     }
2022 
2023     private DateTimeParseContext parseUnresolved0(CharSequence text, ParsePosition position) {
2024         Objects.requireNonNull(text, "text");
2025         Objects.requireNonNull(position, "position");
2026         DateTimeParseContext context = new DateTimeParseContext(this);
2027         int pos = position.getIndex();
2028         pos = printerParser.parse(context, text, pos);
2029         if (pos < 0) {
2030             position.setErrorIndex(~pos);  // index not updated from input
2031             return null;
2032         }
2033         position.setIndex(pos);  // errorIndex not updated from input
2034         return context;
2035     }
2036 
2037     //-----------------------------------------------------------------------
2038     /**
2039      * Returns the formatter as a composite printer parser.
2040      *
2041      * @param optional  whether the printer/parser should be optional
2042      * @return the printer/parser, not null
2043      */
2044     CompositePrinterParser toPrinterParser(boolean optional) {
2045         return printerParser.withOptional(optional);
2046     }
2047 
2048     /**
2049      * Returns this formatter as a {@code java.text.Format} instance.
2050      * <p>
2051      * The returned {@link Format} instance will format any {@link TemporalAccessor}
2052      * and parses to a resolved {@link TemporalAccessor}.
2053      * <p>
2054      * Exceptions will follow the definitions of {@code Format}, see those methods
2055      * for details about {@code IllegalArgumentException} during formatting and
2056      * {@code ParseException} or null during parsing.
2057      * The format does not support attributing of the returned format string.
2058      *
2059      * @return this formatter as a classic format instance, not null
2060      */
2061     public Format toFormat() {
2062         return new ClassicFormat(this, null);
2063     }
2064 
2065     /**
2066      * Returns this formatter as a {@code java.text.Format} instance that will
2067      * parse using the specified query.
2068      * <p>
2069      * The returned {@link Format} instance will format any {@link TemporalAccessor}
2070      * and parses to the type specified.
2071      * The type must be one that is supported by {@link #parse}.
2072      * <p>
2073      * Exceptions will follow the definitions of {@code Format}, see those methods
2074      * for details about {@code IllegalArgumentException} during formatting and
2075      * {@code ParseException} or null during parsing.
2076      * The format does not support attributing of the returned format string.
2077      *
2078      * @param parseQuery  the query defining the type to parse to, not null
2079      * @return this formatter as a classic format instance, not null
2080      */
2081     public Format toFormat(TemporalQuery<?> parseQuery) {
2082         Objects.requireNonNull(parseQuery, "parseQuery");
2083         return new ClassicFormat(this, parseQuery);
2084     }
2085 
2086     //-----------------------------------------------------------------------
2087     /**
2088      * Returns a description of the underlying formatters.
2089      *
2090      * @return a description of this formatter, not null
2091      */
2092     @Override
2093     public String toString() {
2094         String pattern = printerParser.toString();
2095         pattern = pattern.startsWith("[") ? pattern : pattern.substring(1, pattern.length() - 1);
2096         return pattern;
2097         // TODO: Fix tests to not depend on toString()
2098 //        return "DateTimeFormatter[" + locale +
2099 //                (chrono != null ? "," + chrono : "") +
2100 //                (zone != null ? "," + zone : "") +
2101 //                pattern + "]";
2102     }
2103 
2104     //-----------------------------------------------------------------------
2105     /**
2106      * Implements the classic Java Format API.
2107      * @serial exclude
2108      */
2109     @SuppressWarnings("serial")  // not actually serializable
2110     static class ClassicFormat extends Format {
2111         /** The formatter. */
2112         private final DateTimeFormatter formatter;
2113         /** The type to be parsed. */
2114         private final TemporalQuery<?> parseType;
2115         /** Constructor. */
2116         public ClassicFormat(DateTimeFormatter formatter, TemporalQuery<?> parseType) {
2117             this.formatter = formatter;
2118             this.parseType = parseType;
2119         }
2120 
2121         @Override
2122         public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
2123             Objects.requireNonNull(obj, "obj");
2124             Objects.requireNonNull(toAppendTo, "toAppendTo");
2125             Objects.requireNonNull(pos, "pos");
2126             if (obj instanceof TemporalAccessor == false) {
2127                 throw new IllegalArgumentException("Format target must implement TemporalAccessor");
2128             }
2129             pos.setBeginIndex(0);
2130             pos.setEndIndex(0);
2131             try {
2132                 formatter.formatTo((TemporalAccessor) obj, toAppendTo);
2133             } catch (RuntimeException ex) {
2134                 throw new IllegalArgumentException(ex.getMessage(), ex);
2135             }
2136             return toAppendTo;
2137         }
2138         @Override
2139         public Object parseObject(String text) throws ParseException {
2140             Objects.requireNonNull(text, "text");
2141             try {
2142                 if (parseType == null) {
2143                     return formatter.parseResolved0(text, null);
2144                 }
2145                 return formatter.parse(text, parseType);
2146             } catch (DateTimeParseException ex) {
2147                 throw new ParseException(ex.getMessage(), ex.getErrorIndex());
2148             } catch (RuntimeException ex) {
2149                 throw (ParseException) new ParseException(ex.getMessage(), 0).initCause(ex);
2150             }
2151         }
2152         @Override
2153         public Object parseObject(String text, ParsePosition pos) {
2154             Objects.requireNonNull(text, "text");
2155             DateTimeParseContext context;
2156             try {
2157                 context = formatter.parseUnresolved0(text, pos);
2158             } catch (IndexOutOfBoundsException ex) {
2159                 if (pos.getErrorIndex() < 0) {
2160                     pos.setErrorIndex(0);
2161                 }
2162                 return null;
2163             }
2164             if (context == null) {
2165                 if (pos.getErrorIndex() < 0) {
2166                     pos.setErrorIndex(0);
2167                 }
2168                 return null;
2169             }
2170             try {
2171                 TemporalAccessor resolved = context.toResolved(formatter.resolverStyle, formatter.resolverFields);
2172                 if (parseType == null) {
2173                     return resolved;
2174                 }
2175                 return resolved.query(parseType);
2176             } catch (RuntimeException ex) {
2177                 pos.setErrorIndex(0);
2178                 return null;
2179             }
2180         }
2181     }
2182 
2183 }