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