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