1 /*
   2  * Copyright (c) 2012, 2016, 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.HOUR_OF_DAY;
  66 import static java.time.temporal.ChronoField.INSTANT_SECONDS;
  67 import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
  68 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  69 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
  70 import static java.time.temporal.ChronoField.OFFSET_SECONDS;
  71 import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
  72 import static java.time.temporal.ChronoField.YEAR;
  73 import static java.time.temporal.ChronoField.ERA;
  74 
  75 import java.lang.ref.SoftReference;
  76 import java.math.BigDecimal;
  77 import java.math.BigInteger;
  78 import java.math.RoundingMode;
  79 import java.text.ParsePosition;
  80 import java.time.DateTimeException;
  81 import java.time.Instant;
  82 import java.time.LocalDate;
  83 import java.time.LocalDateTime;
  84 import java.time.ZoneId;
  85 import java.time.ZoneOffset;
  86 import java.time.chrono.ChronoLocalDate;
  87 import java.time.chrono.Chronology;
  88 import java.time.chrono.Era;
  89 import java.time.chrono.IsoChronology;
  90 import java.time.format.DateTimeTextProvider.LocaleStore;
  91 import java.time.temporal.ChronoField;
  92 import java.time.temporal.IsoFields;
  93 import java.time.temporal.TemporalAccessor;
  94 import java.time.temporal.TemporalField;
  95 import java.time.temporal.TemporalQueries;
  96 import java.time.temporal.TemporalQuery;
  97 import java.time.temporal.ValueRange;
  98 import java.time.temporal.WeekFields;
  99 import java.time.zone.ZoneRulesProvider;
 100 import java.util.AbstractMap.SimpleImmutableEntry;
 101 import java.util.ArrayList;
 102 import java.util.Arrays;
 103 import java.util.Collections;
 104 import java.util.Comparator;
 105 import java.util.HashMap;
 106 import java.util.HashSet;
 107 import java.util.Iterator;
 108 import java.util.LinkedHashMap;
 109 import java.util.List;
 110 import java.util.Locale;
 111 import java.util.Map;
 112 import java.util.Map.Entry;
 113 import java.util.Objects;
 114 import java.util.Set;
 115 import java.util.TimeZone;
 116 import java.util.concurrent.ConcurrentHashMap;
 117 import java.util.concurrent.ConcurrentMap;
 118 
 119 import sun.util.locale.provider.LocaleProviderAdapter;
 120 import sun.util.locale.provider.LocaleResources;
 121 import sun.util.locale.provider.TimeZoneNameUtility;
 122 
 123 /**
 124  * Builder to create date-time formatters.
 125  * <p>
 126  * This allows a {@code DateTimeFormatter} to be created.
 127  * All date-time formatters are created ultimately using this builder.
 128  * <p>
 129  * The basic elements of date-time can all be added:
 130  * <ul>
 131  * <li>Value - a numeric value</li>
 132  * <li>Fraction - a fractional value including the decimal place. Always use this when
 133  * outputting fractions to ensure that the fraction is parsed correctly</li>
 134  * <li>Text - the textual equivalent for the value</li>
 135  * <li>OffsetId/Offset - the {@linkplain ZoneOffset zone offset}</li>
 136  * <li>ZoneId - the {@linkplain ZoneId time-zone} id</li>
 137  * <li>ZoneText - the name of the time-zone</li>
 138  * <li>ChronologyId - the {@linkplain Chronology chronology} id</li>
 139  * <li>ChronologyText - the name of the chronology</li>
 140  * <li>Literal - a text literal</li>
 141  * <li>Nested and Optional - formats can be nested or made optional</li>
 142  * </ul>
 143  * In addition, any of the elements may be decorated by padding, either with spaces or any other character.
 144  * <p>
 145  * Finally, a shorthand pattern, mostly compatible with {@code java.text.SimpleDateFormat SimpleDateFormat}
 146  * can be used, see {@link #appendPattern(String)}.
 147  * In practice, this simply parses the pattern and calls other methods on the builder.
 148  *
 149  * @implSpec
 150  * This class is a mutable builder intended for use from a single thread.
 151  *
 152  * @since 1.8
 153  */
 154 public final class DateTimeFormatterBuilder {
 155 
 156     /**
 157      * Query for a time-zone that is region-only.
 158      */
 159     private static final TemporalQuery<ZoneId> QUERY_REGION_ONLY = (temporal) -> {
 160         ZoneId zone = temporal.query(TemporalQueries.zoneId());
 161         return (zone != null && zone instanceof ZoneOffset == false ? zone : null);
 162     };
 163 
 164     /**
 165      * The currently active builder, used by the outermost builder.
 166      */
 167     private DateTimeFormatterBuilder active = this;
 168     /**
 169      * The parent builder, null for the outermost builder.
 170      */
 171     private final DateTimeFormatterBuilder parent;
 172     /**
 173      * The list of printers that will be used.
 174      */
 175     private final List<DateTimePrinterParser> printerParsers = new ArrayList<>();
 176     /**
 177      * Whether this builder produces an optional formatter.
 178      */
 179     private final boolean optional;
 180     /**
 181      * The width to pad the next field to.
 182      */
 183     private int padNextWidth;
 184     /**
 185      * The character to pad the next field with.
 186      */
 187     private char padNextChar;
 188     /**
 189      * The index of the last variable width value parser.
 190      */
 191     private int valueParserIndex = -1;
 192 
 193     /**
 194      * Gets the formatting pattern for date and time styles for a locale and chronology.
 195      * The locale and chronology are used to lookup the locale specific format
 196      * for the requested dateStyle and/or timeStyle.
 197      *
 198      * @param dateStyle  the FormatStyle for the date, null for time-only pattern
 199      * @param timeStyle  the FormatStyle for the time, null for date-only pattern
 200      * @param chrono  the Chronology, non-null
 201      * @param locale  the locale, non-null
 202      * @return the locale and Chronology specific formatting pattern
 203      * @throws IllegalArgumentException if both dateStyle and timeStyle are null
 204      */
 205     public static String getLocalizedDateTimePattern(FormatStyle dateStyle, FormatStyle timeStyle,
 206             Chronology chrono, Locale locale) {
 207         Objects.requireNonNull(locale, "locale");
 208         Objects.requireNonNull(chrono, "chrono");
 209         if (dateStyle == null && timeStyle == null) {
 210             throw new IllegalArgumentException("Either dateStyle or timeStyle must be non-null");
 211         }
 212         LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased().getLocaleResources(locale);
 213         String pattern = lr.getJavaTimeDateTimePattern(
 214                 convertStyle(timeStyle), convertStyle(dateStyle), chrono.getCalendarType());
 215         return pattern;
 216     }
 217 
 218     /**
 219      * Converts the given FormatStyle to the java.text.DateFormat style.
 220      *
 221      * @param style  the FormatStyle style
 222      * @return the int style, or -1 if style is null, indicating un-required
 223      */
 224     private static int convertStyle(FormatStyle style) {
 225         if (style == null) {
 226             return -1;
 227         }
 228         return style.ordinal();  // indices happen to align
 229     }
 230 
 231     /**
 232      * Constructs a new instance of the builder.
 233      */
 234     public DateTimeFormatterBuilder() {
 235         super();
 236         parent = null;
 237         optional = false;
 238     }
 239 
 240     /**
 241      * Constructs a new instance of the builder.
 242      *
 243      * @param parent  the parent builder, not null
 244      * @param optional  whether the formatter is optional, not null
 245      */
 246     private DateTimeFormatterBuilder(DateTimeFormatterBuilder parent, boolean optional) {
 247         super();
 248         this.parent = parent;
 249         this.optional = optional;
 250     }
 251 
 252     //-----------------------------------------------------------------------
 253     /**
 254      * Changes the parse style to be case sensitive for the remainder of the formatter.
 255      * <p>
 256      * Parsing can be case sensitive or insensitive - by default it is case sensitive.
 257      * This method allows the case sensitivity setting of parsing to be changed.
 258      * <p>
 259      * Calling this method changes the state of the builder such that all
 260      * subsequent builder method calls will parse text in case sensitive mode.
 261      * See {@link #parseCaseInsensitive} for the opposite setting.
 262      * The parse case sensitive/insensitive methods may be called at any point
 263      * in the builder, thus the parser can swap between case parsing modes
 264      * multiple times during the parse.
 265      * <p>
 266      * Since the default is case sensitive, this method should only be used after
 267      * a previous call to {@code #parseCaseInsensitive}.
 268      *
 269      * @return this, for chaining, not null
 270      */
 271     public DateTimeFormatterBuilder parseCaseSensitive() {
 272         appendInternal(SettingsParser.SENSITIVE);
 273         return this;
 274     }
 275 
 276     /**
 277      * Changes the parse style to be case insensitive for the remainder of the formatter.
 278      * <p>
 279      * Parsing can be case sensitive or insensitive - by default it is case sensitive.
 280      * This method allows the case sensitivity setting of parsing to be changed.
 281      * <p>
 282      * Calling this method changes the state of the builder such that all
 283      * subsequent builder method calls will parse text in case insensitive mode.
 284      * See {@link #parseCaseSensitive()} for the opposite setting.
 285      * The parse case sensitive/insensitive methods may be called at any point
 286      * in the builder, thus the parser can swap between case parsing modes
 287      * multiple times during the parse.
 288      *
 289      * @return this, for chaining, not null
 290      */
 291     public DateTimeFormatterBuilder parseCaseInsensitive() {
 292         appendInternal(SettingsParser.INSENSITIVE);
 293         return this;
 294     }
 295 
 296     //-----------------------------------------------------------------------
 297     /**
 298      * Changes the parse style to be strict for the remainder of the formatter.
 299      * <p>
 300      * Parsing can be strict or lenient - by default its strict.
 301      * This controls the degree of flexibility in matching the text and sign styles.
 302      * <p>
 303      * When used, this method changes the parsing to be strict from this point onwards.
 304      * As strict is the default, this is normally only needed after calling {@link #parseLenient()}.
 305      * The change will remain in force until the end of the formatter that is eventually
 306      * constructed or until {@code parseLenient} is called.
 307      *
 308      * @return this, for chaining, not null
 309      */
 310     public DateTimeFormatterBuilder parseStrict() {
 311         appendInternal(SettingsParser.STRICT);
 312         return this;
 313     }
 314 
 315     /**
 316      * Changes the parse style to be lenient for the remainder of the formatter.
 317      * Note that case sensitivity is set separately to this method.
 318      * <p>
 319      * Parsing can be strict or lenient - by default its strict.
 320      * This controls the degree of flexibility in matching the text and sign styles.
 321      * Applications calling this method should typically also call {@link #parseCaseInsensitive()}.
 322      * <p>
 323      * When used, this method changes the parsing to be lenient from this point onwards.
 324      * The change will remain in force until the end of the formatter that is eventually
 325      * constructed or until {@code parseStrict} is called.
 326      *
 327      * @return this, for chaining, not null
 328      */
 329     public DateTimeFormatterBuilder parseLenient() {
 330         appendInternal(SettingsParser.LENIENT);
 331         return this;
 332     }
 333 
 334     //-----------------------------------------------------------------------
 335     /**
 336      * Appends a default value for a field to the formatter for use in parsing.
 337      * <p>
 338      * This appends an instruction to the builder to inject a default value
 339      * into the parsed result. This is especially useful in conjunction with
 340      * optional parts of the formatter.
 341      * <p>
 342      * For example, consider a formatter that parses the year, followed by
 343      * an optional month, with a further optional day-of-month. Using such a
 344      * formatter would require the calling code to check whether a full date,
 345      * year-month or just a year had been parsed. This method can be used to
 346      * default the month and day-of-month to a sensible value, such as the
 347      * first of the month, allowing the calling code to always get a date.
 348      * <p>
 349      * During formatting, this method has no effect.
 350      * <p>
 351      * During parsing, the current state of the parse is inspected.
 352      * If the specified field has no associated value, because it has not been
 353      * parsed successfully at that point, then the specified value is injected
 354      * into the parse result. Injection is immediate, thus the field-value pair
 355      * will be visible to any subsequent elements in the formatter.
 356      * As such, this method is normally called at the end of the builder.
 357      *
 358      * @param field  the field to default the value of, not null
 359      * @param value  the value to default the field to
 360      * @return this, for chaining, not null
 361      */
 362     public DateTimeFormatterBuilder parseDefaulting(TemporalField field, long value) {
 363         Objects.requireNonNull(field, "field");
 364         appendInternal(new DefaultValueParser(field, value));
 365         return this;
 366     }
 367 
 368     //-----------------------------------------------------------------------
 369     /**
 370      * Appends the value of a date-time field to the formatter using a normal
 371      * output style.
 372      * <p>
 373      * The value of the field will be output during a format.
 374      * If the value cannot be obtained then an exception will be thrown.
 375      * <p>
 376      * The value will be printed as per the normal format of an integer value.
 377      * Only negative numbers will be signed. No padding will be added.
 378      * <p>
 379      * The parser for a variable width value such as this normally behaves greedily,
 380      * requiring one digit, but accepting as many digits as possible.
 381      * This behavior can be affected by 'adjacent value parsing'.
 382      * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details.
 383      *
 384      * @param field  the field to append, not null
 385      * @return this, for chaining, not null
 386      */
 387     public DateTimeFormatterBuilder appendValue(TemporalField field) {
 388         Objects.requireNonNull(field, "field");
 389         appendValue(new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL));
 390         return this;
 391     }
 392 
 393     /**
 394      * Appends the value of a date-time field to the formatter using a fixed
 395      * width, zero-padded approach.
 396      * <p>
 397      * The value of the field will be output during a format.
 398      * If the value cannot be obtained then an exception will be thrown.
 399      * <p>
 400      * The value will be zero-padded on the left. If the size of the value
 401      * means that it cannot be printed within the width then an exception is thrown.
 402      * If the value of the field is negative then an exception is thrown during formatting.
 403      * <p>
 404      * This method supports a special technique of parsing known as 'adjacent value parsing'.
 405      * This technique solves the problem where a value, variable or fixed width, is followed by one or more
 406      * fixed length values. The standard parser is greedy, and thus it would normally
 407      * steal the digits that are needed by the fixed width value parsers that follow the
 408      * variable width one.
 409      * <p>
 410      * No action is required to initiate 'adjacent value parsing'.
 411      * When a call to {@code appendValue} is made, the builder
 412      * enters adjacent value parsing setup mode. If the immediately subsequent method
 413      * call or calls on the same builder are for a fixed width value, then the parser will reserve
 414      * space so that the fixed width values can be parsed.
 415      * <p>
 416      * For example, consider {@code builder.appendValue(YEAR).appendValue(MONTH_OF_YEAR, 2);}
 417      * The year is a variable width parse of between 1 and 19 digits.
 418      * The month is a fixed width parse of 2 digits.
 419      * Because these were appended to the same builder immediately after one another,
 420      * the year parser will reserve two digits for the month to parse.
 421      * Thus, the text '201106' will correctly parse to a year of 2011 and a month of 6.
 422      * Without adjacent value parsing, the year would greedily parse all six digits and leave
 423      * nothing for the month.
 424      * <p>
 425      * Adjacent value parsing applies to each set of fixed width not-negative values in the parser
 426      * that immediately follow any kind of value, variable or fixed width.
 427      * Calling any other append method will end the setup of adjacent value parsing.
 428      * Thus, in the unlikely event that you need to avoid adjacent value parsing behavior,
 429      * simply add the {@code appendValue} to another {@code DateTimeFormatterBuilder}
 430      * and add that to this builder.
 431      * <p>
 432      * If adjacent parsing is active, then parsing must match exactly the specified
 433      * number of digits in both strict and lenient modes.
 434      * In addition, no positive or negative sign is permitted.
 435      *
 436      * @param field  the field to append, not null
 437      * @param width  the width of the printed field, from 1 to 19
 438      * @return this, for chaining, not null
 439      * @throws IllegalArgumentException if the width is invalid
 440      */
 441     public DateTimeFormatterBuilder appendValue(TemporalField field, int width) {
 442         Objects.requireNonNull(field, "field");
 443         if (width < 1 || width > 19) {
 444             throw new IllegalArgumentException("The width must be from 1 to 19 inclusive but was " + width);
 445         }
 446         NumberPrinterParser pp = new NumberPrinterParser(field, width, width, SignStyle.NOT_NEGATIVE);
 447         appendValue(pp);
 448         return this;
 449     }
 450 
 451     /**
 452      * Appends the value of a date-time field to the formatter providing full
 453      * control over formatting.
 454      * <p>
 455      * The value of the field will be output during a format.
 456      * If the value cannot be obtained then an exception will be thrown.
 457      * <p>
 458      * This method provides full control of the numeric formatting, including
 459      * zero-padding and the positive/negative sign.
 460      * <p>
 461      * The parser for a variable width value such as this normally behaves greedily,
 462      * accepting as many digits as possible.
 463      * This behavior can be affected by 'adjacent value parsing'.
 464      * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details.
 465      * <p>
 466      * In strict parsing mode, the minimum number of parsed digits is {@code minWidth}
 467      * and the maximum is {@code maxWidth}.
 468      * In lenient parsing mode, the minimum number of parsed digits is one
 469      * and the maximum is 19 (except as limited by adjacent value parsing).
 470      * <p>
 471      * If this method is invoked with equal minimum and maximum widths and a sign style of
 472      * {@code NOT_NEGATIVE} then it delegates to {@code appendValue(TemporalField,int)}.
 473      * In this scenario, the formatting and parsing behavior described there occur.
 474      *
 475      * @param field  the field to append, not null
 476      * @param minWidth  the minimum field width of the printed field, from 1 to 19
 477      * @param maxWidth  the maximum field width of the printed field, from 1 to 19
 478      * @param signStyle  the positive/negative output style, not null
 479      * @return this, for chaining, not null
 480      * @throws IllegalArgumentException if the widths are invalid
 481      */
 482     public DateTimeFormatterBuilder appendValue(
 483             TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) {
 484         if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) {
 485             return appendValue(field, maxWidth);
 486         }
 487         Objects.requireNonNull(field, "field");
 488         Objects.requireNonNull(signStyle, "signStyle");
 489         if (minWidth < 1 || minWidth > 19) {
 490             throw new IllegalArgumentException("The minimum width must be from 1 to 19 inclusive but was " + minWidth);
 491         }
 492         if (maxWidth < 1 || maxWidth > 19) {
 493             throw new IllegalArgumentException("The maximum width must be from 1 to 19 inclusive but was " + maxWidth);
 494         }
 495         if (maxWidth < minWidth) {
 496             throw new IllegalArgumentException("The maximum width must exceed or equal the minimum width but " +
 497                     maxWidth + " < " + minWidth);
 498         }
 499         NumberPrinterParser pp = new NumberPrinterParser(field, minWidth, maxWidth, signStyle);
 500         appendValue(pp);
 501         return this;
 502     }
 503 
 504     //-----------------------------------------------------------------------
 505     /**
 506      * Appends the reduced value of a date-time field to the formatter.
 507      * <p>
 508      * Since fields such as year vary by chronology, it is recommended to use the
 509      * {@link #appendValueReduced(TemporalField, int, int, ChronoLocalDate)} date}
 510      * variant of this method in most cases. This variant is suitable for
 511      * simple fields or working with only the ISO chronology.
 512      * <p>
 513      * For formatting, the {@code width} and {@code maxWidth} are used to
 514      * determine the number of characters to format.
 515      * If they are equal then the format is fixed width.
 516      * If the value of the field is within the range of the {@code baseValue} using
 517      * {@code width} characters then the reduced value is formatted otherwise the value is
 518      * truncated to fit {@code maxWidth}.
 519      * The rightmost characters are output to match the width, left padding with zero.
 520      * <p>
 521      * For strict parsing, the number of characters allowed by {@code width} to {@code maxWidth} are parsed.
 522      * For lenient parsing, the number of characters must be at least 1 and less than 10.
 523      * If the number of digits parsed is equal to {@code width} and the value is positive,
 524      * the value of the field is computed to be the first number greater than
 525      * or equal to the {@code baseValue} with the same least significant characters,
 526      * otherwise the value parsed is the field value.
 527      * This allows a reduced value to be entered for values in range of the baseValue
 528      * and width and absolute values can be entered for values outside the range.
 529      * <p>
 530      * For example, a base value of {@code 1980} and a width of {@code 2} will have
 531      * valid values from {@code 1980} to {@code 2079}.
 532      * During parsing, the text {@code "12"} will result in the value {@code 2012} as that
 533      * is the value within the range where the last two characters are "12".
 534      * By contrast, parsing the text {@code "1915"} will result in the value {@code 1915}.
 535      *
 536      * @param field  the field to append, not null
 537      * @param width  the field width of the printed and parsed field, from 1 to 10
 538      * @param maxWidth  the maximum field width of the printed field, from 1 to 10
 539      * @param baseValue  the base value of the range of valid values
 540      * @return this, for chaining, not null
 541      * @throws IllegalArgumentException if the width or base value is invalid
 542      */
 543     public DateTimeFormatterBuilder appendValueReduced(TemporalField field,
 544             int width, int maxWidth, int baseValue) {
 545         Objects.requireNonNull(field, "field");
 546         ReducedPrinterParser pp = new ReducedPrinterParser(field, width, maxWidth, baseValue, null);
 547         appendValue(pp);
 548         return this;
 549     }
 550 
 551     /**
 552      * Appends the reduced value of a date-time field to the formatter.
 553      * <p>
 554      * This is typically used for formatting and parsing a two digit year.
 555      * <p>
 556      * The base date is used to calculate the full value during parsing.
 557      * For example, if the base date is 1950-01-01 then parsed values for
 558      * a two digit year parse will be in the range 1950-01-01 to 2049-12-31.
 559      * Only the year would be extracted from the date, thus a base date of
 560      * 1950-08-25 would also parse to the range 1950-01-01 to 2049-12-31.
 561      * This behavior is necessary to support fields such as week-based-year
 562      * or other calendar systems where the parsed value does not align with
 563      * standard ISO years.
 564      * <p>
 565      * The exact behavior is as follows. Parse the full set of fields and
 566      * determine the effective chronology using the last chronology if
 567      * it appears more than once. Then convert the base date to the
 568      * effective chronology. Then extract the specified field from the
 569      * chronology-specific base date and use it to determine the
 570      * {@code baseValue} used below.
 571      * <p>
 572      * For formatting, the {@code width} and {@code maxWidth} are used to
 573      * determine the number of characters to format.
 574      * If they are equal then the format is fixed width.
 575      * If the value of the field is within the range of the {@code baseValue} using
 576      * {@code width} characters then the reduced value is formatted otherwise the value is
 577      * truncated to fit {@code maxWidth}.
 578      * The rightmost characters are output to match the width, left padding with zero.
 579      * <p>
 580      * For strict parsing, the number of characters allowed by {@code width} to {@code maxWidth} are parsed.
 581      * For lenient parsing, the number of characters must be at least 1 and less than 10.
 582      * If the number of digits parsed is equal to {@code width} and the value is positive,
 583      * the value of the field is computed to be the first number greater than
 584      * or equal to the {@code baseValue} with the same least significant characters,
 585      * otherwise the value parsed is the field value.
 586      * This allows a reduced value to be entered for values in range of the baseValue
 587      * and width and absolute values can be entered for values outside the range.
 588      * <p>
 589      * For example, a base value of {@code 1980} and a width of {@code 2} will have
 590      * valid values from {@code 1980} to {@code 2079}.
 591      * During parsing, the text {@code "12"} will result in the value {@code 2012} as that
 592      * is the value within the range where the last two characters are "12".
 593      * By contrast, parsing the text {@code "1915"} will result in the value {@code 1915}.
 594      *
 595      * @param field  the field to append, not null
 596      * @param width  the field width of the printed and parsed field, from 1 to 10
 597      * @param maxWidth  the maximum field width of the printed field, from 1 to 10
 598      * @param baseDate  the base date used to calculate the base value for the range
 599      *  of valid values in the parsed chronology, not null
 600      * @return this, for chaining, not null
 601      * @throws IllegalArgumentException if the width or base value is invalid
 602      */
 603     public DateTimeFormatterBuilder appendValueReduced(
 604             TemporalField field, int width, int maxWidth, ChronoLocalDate baseDate) {
 605         Objects.requireNonNull(field, "field");
 606         Objects.requireNonNull(baseDate, "baseDate");
 607         ReducedPrinterParser pp = new ReducedPrinterParser(field, width, maxWidth, 0, baseDate);
 608         appendValue(pp);
 609         return this;
 610     }
 611 
 612     /**
 613      * Appends a fixed or variable width printer-parser handling adjacent value mode.
 614      * If a PrinterParser is not active then the new PrinterParser becomes
 615      * the active PrinterParser.
 616      * Otherwise, the active PrinterParser is modified depending on the new PrinterParser.
 617      * If the new PrinterParser is fixed width and has sign style {@code NOT_NEGATIVE}
 618      * then its width is added to the active PP and
 619      * the new PrinterParser is forced to be fixed width.
 620      * If the new PrinterParser is variable width, the active PrinterParser is changed
 621      * to be fixed width and the new PrinterParser becomes the active PP.
 622      *
 623      * @param pp  the printer-parser, not null
 624      * @return this, for chaining, not null
 625      */
 626     private DateTimeFormatterBuilder appendValue(NumberPrinterParser pp) {
 627         if (active.valueParserIndex >= 0) {
 628             final int activeValueParser = active.valueParserIndex;
 629 
 630             // adjacent parsing mode, update setting in previous parsers
 631             NumberPrinterParser basePP = (NumberPrinterParser) active.printerParsers.get(activeValueParser);
 632             if (pp.minWidth == pp.maxWidth && pp.signStyle == SignStyle.NOT_NEGATIVE) {
 633                 // Append the width to the subsequentWidth of the active parser
 634                 basePP = basePP.withSubsequentWidth(pp.maxWidth);
 635                 // Append the new parser as a fixed width
 636                 appendInternal(pp.withFixedWidth());
 637                 // Retain the previous active parser
 638                 active.valueParserIndex = activeValueParser;
 639             } else {
 640                 // Modify the active parser to be fixed width
 641                 basePP = basePP.withFixedWidth();
 642                 // The new parser becomes the mew active parser
 643                 active.valueParserIndex = appendInternal(pp);
 644             }
 645             // Replace the modified parser with the updated one
 646             active.printerParsers.set(activeValueParser, basePP);
 647         } else {
 648             // The new Parser becomes the active parser
 649             active.valueParserIndex = appendInternal(pp);
 650         }
 651         return this;
 652     }
 653 
 654     //-----------------------------------------------------------------------
 655     /**
 656      * Appends the fractional value of a date-time field to the formatter.
 657      * <p>
 658      * The fractional value of the field will be output including the
 659      * preceding decimal point. The preceding value is not output.
 660      * For example, the second-of-minute value of 15 would be output as {@code .25}.
 661      * <p>
 662      * The width of the printed fraction can be controlled. Setting the
 663      * minimum width to zero will cause no output to be generated.
 664      * The printed fraction will have the minimum width necessary between
 665      * the minimum and maximum widths - trailing zeroes are omitted.
 666      * No rounding occurs due to the maximum width - digits are simply dropped.
 667      * <p>
 668      * When parsing in strict mode, the number of parsed digits must be between
 669      * the minimum and maximum width. When parsing in lenient mode, the minimum
 670      * width is considered to be zero and the maximum is nine.
 671      * <p>
 672      * If the value cannot be obtained then an exception will be thrown.
 673      * If the value is negative an exception will be thrown.
 674      * If the field does not have a fixed set of valid values then an
 675      * exception will be thrown.
 676      * If the field value in the date-time to be printed is invalid it
 677      * cannot be printed and an exception will be thrown.
 678      *
 679      * @param field  the field to append, not null
 680      * @param minWidth  the minimum width of the field excluding the decimal point, from 0 to 9
 681      * @param maxWidth  the maximum width of the field excluding the decimal point, from 1 to 9
 682      * @param decimalPoint  whether to output the localized decimal point symbol
 683      * @return this, for chaining, not null
 684      * @throws IllegalArgumentException if the field has a variable set of valid values or
 685      *  either width is invalid
 686      */
 687     public DateTimeFormatterBuilder appendFraction(
 688             TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) {
 689         appendInternal(new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint));
 690         return this;
 691     }
 692 
 693     //-----------------------------------------------------------------------
 694     /**
 695      * Appends the text of a date-time field to the formatter using the full
 696      * text style.
 697      * <p>
 698      * The text of the field will be output during a format.
 699      * The value must be within the valid range of the field.
 700      * If the value cannot be obtained then an exception will be thrown.
 701      * If the field has no textual representation, then the numeric value will be used.
 702      * <p>
 703      * The value will be printed as per the normal format of an integer value.
 704      * Only negative numbers will be signed. No padding will be added.
 705      *
 706      * @param field  the field to append, not null
 707      * @return this, for chaining, not null
 708      */
 709     public DateTimeFormatterBuilder appendText(TemporalField field) {
 710         return appendText(field, TextStyle.FULL);
 711     }
 712 
 713     /**
 714      * Appends the text of a date-time field to the formatter.
 715      * <p>
 716      * The text of the field will be output during a format.
 717      * The value must be within the valid range of the field.
 718      * If the value cannot be obtained then an exception will be thrown.
 719      * If the field has no textual representation, then the numeric value will be used.
 720      * <p>
 721      * The value will be printed as per the normal format of an integer value.
 722      * Only negative numbers will be signed. No padding will be added.
 723      *
 724      * @param field  the field to append, not null
 725      * @param textStyle  the text style to use, not null
 726      * @return this, for chaining, not null
 727      */
 728     public DateTimeFormatterBuilder appendText(TemporalField field, TextStyle textStyle) {
 729         Objects.requireNonNull(field, "field");
 730         Objects.requireNonNull(textStyle, "textStyle");
 731         appendInternal(new TextPrinterParser(field, textStyle, DateTimeTextProvider.getInstance()));
 732         return this;
 733     }
 734 
 735     /**
 736      * Appends the text of a date-time field to the formatter using the specified
 737      * map to supply the text.
 738      * <p>
 739      * The standard text outputting methods use the localized text in the JDK.
 740      * This method allows that text to be specified directly.
 741      * The supplied map is not validated by the builder to ensure that formatting or
 742      * parsing is possible, thus an invalid map may throw an error during later use.
 743      * <p>
 744      * Supplying the map of text provides considerable flexibility in formatting and parsing.
 745      * For example, a legacy application might require or supply the months of the
 746      * year as "JNY", "FBY", "MCH" etc. These do not match the standard set of text
 747      * for localized month names. Using this method, a map can be created which
 748      * defines the connection between each value and the text:
 749      * <pre>
 750      * Map&lt;Long, String&gt; map = new HashMap&lt;&gt;();
 751      * map.put(1L, "JNY");
 752      * map.put(2L, "FBY");
 753      * map.put(3L, "MCH");
 754      * ...
 755      * builder.appendText(MONTH_OF_YEAR, map);
 756      * </pre>
 757      * <p>
 758      * Other uses might be to output the value with a suffix, such as "1st", "2nd", "3rd",
 759      * or as Roman numerals "I", "II", "III", "IV".
 760      * <p>
 761      * During formatting, the value is obtained and checked that it is in the valid range.
 762      * If text is not available for the value then it is output as a number.
 763      * During parsing, the parser will match against the map of text and numeric values.
 764      *
 765      * @param field  the field to append, not null
 766      * @param textLookup  the map from the value to the text
 767      * @return this, for chaining, not null
 768      */
 769     public DateTimeFormatterBuilder appendText(TemporalField field, Map<Long, String> textLookup) {
 770         Objects.requireNonNull(field, "field");
 771         Objects.requireNonNull(textLookup, "textLookup");
 772         Map<Long, String> copy = new LinkedHashMap<>(textLookup);
 773         Map<TextStyle, Map<Long, String>> map = Collections.singletonMap(TextStyle.FULL, copy);
 774         final LocaleStore store = new LocaleStore(map);
 775         DateTimeTextProvider provider = new DateTimeTextProvider() {
 776             @Override
 777             public String getText(TemporalField field, long value, TextStyle style, Locale locale) {
 778                 return store.getText(value, style);
 779             }
 780             @Override
 781             public Iterator<Entry<String, Long>> getTextIterator(TemporalField field, TextStyle style, Locale locale) {
 782                 return store.getTextIterator(style);
 783             }
 784         };
 785         appendInternal(new TextPrinterParser(field, TextStyle.FULL, provider));
 786         return this;
 787     }
 788 
 789     //-----------------------------------------------------------------------
 790     /**
 791      * Appends an instant using ISO-8601 to the formatter, formatting fractional
 792      * digits in groups of three.
 793      * <p>
 794      * Instants have a fixed output format.
 795      * They are converted to a date-time with a zone-offset of UTC and formatted
 796      * using the standard ISO-8601 format.
 797      * With this method, formatting nano-of-second outputs zero, three, six
 798      * or nine digits as necessary.
 799      * The localized decimal style is not used.
 800      * <p>
 801      * The instant is obtained using {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
 802      * and optionally (@code NANO_OF_SECOND). The value of {@code INSTANT_SECONDS}
 803      * may be outside the maximum range of {@code LocalDateTime}.
 804      * <p>
 805      * The {@linkplain ResolverStyle resolver style} has no effect on instant parsing.
 806      * The end-of-day time of '24:00' is handled as midnight at the start of the following day.
 807      * The leap-second time of '23:59:59' is handled to some degree, see
 808      * {@link DateTimeFormatter#parsedLeapSecond()} for full details.
 809      * <p>
 810      * An alternative to this method is to format/parse the instant as a single
 811      * epoch-seconds value. That is achieved using {@code appendValue(INSTANT_SECONDS)}.
 812      *
 813      * @return this, for chaining, not null
 814      */
 815     public DateTimeFormatterBuilder appendInstant() {
 816         appendInternal(new InstantPrinterParser(-2));
 817         return this;
 818     }
 819 
 820     /**
 821      * Appends an instant using ISO-8601 to the formatter with control over
 822      * the number of fractional digits.
 823      * <p>
 824      * Instants have a fixed output format, although this method provides some
 825      * control over the fractional digits. They are converted to a date-time
 826      * with a zone-offset of UTC and printed using the standard ISO-8601 format.
 827      * The localized decimal style is not used.
 828      * <p>
 829      * The {@code fractionalDigits} parameter allows the output of the fractional
 830      * second to be controlled. Specifying zero will cause no fractional digits
 831      * to be output. From 1 to 9 will output an increasing number of digits, using
 832      * zero right-padding if necessary. The special value -1 is used to output as
 833      * many digits as necessary to avoid any trailing zeroes.
 834      * <p>
 835      * When parsing in strict mode, the number of parsed digits must match the
 836      * fractional digits. When parsing in lenient mode, any number of fractional
 837      * digits from zero to nine are accepted.
 838      * <p>
 839      * The instant is obtained using {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
 840      * and optionally (@code NANO_OF_SECOND). The value of {@code INSTANT_SECONDS}
 841      * may be outside the maximum range of {@code LocalDateTime}.
 842      * <p>
 843      * The {@linkplain ResolverStyle resolver style} has no effect on instant parsing.
 844      * The end-of-day time of '24:00' is handled as midnight at the start of the following day.
 845      * The leap-second time of '23:59:60' is handled to some degree, see
 846      * {@link DateTimeFormatter#parsedLeapSecond()} for full details.
 847      * <p>
 848      * An alternative to this method is to format/parse the instant as a single
 849      * epoch-seconds value. That is achieved using {@code appendValue(INSTANT_SECONDS)}.
 850      *
 851      * @param fractionalDigits  the number of fractional second digits to format with,
 852      *  from 0 to 9, or -1 to use as many digits as necessary
 853      * @return this, for chaining, not null
 854      * @throws IllegalArgumentException if the number of fractional digits is invalid
 855      */
 856     public DateTimeFormatterBuilder appendInstant(int fractionalDigits) {
 857         if (fractionalDigits < -1 || fractionalDigits > 9) {
 858             throw new IllegalArgumentException("The fractional digits must be from -1 to 9 inclusive but was " + fractionalDigits);
 859         }
 860         appendInternal(new InstantPrinterParser(fractionalDigits));
 861         return this;
 862     }
 863 
 864     //-----------------------------------------------------------------------
 865     /**
 866      * Appends the zone offset, such as '+01:00', to the formatter.
 867      * <p>
 868      * This appends an instruction to format/parse the offset ID to the builder.
 869      * This is equivalent to calling {@code appendOffset("+HH:mm:ss", "Z")}.
 870      * See {@link #appendOffset(String, String)} for details on formatting
 871      * and parsing.
 872      *
 873      * @return this, for chaining, not null
 874      */
 875     public DateTimeFormatterBuilder appendOffsetId() {
 876         appendInternal(OffsetIdPrinterParser.INSTANCE_ID_Z);
 877         return this;
 878     }
 879 
 880     /**
 881      * Appends the zone offset, such as '+01:00', to the formatter.
 882      * <p>
 883      * This appends an instruction to format/parse the offset ID to the builder.
 884      * <p>
 885      * During formatting, the offset is obtained using a mechanism equivalent
 886      * to querying the temporal with {@link TemporalQueries#offset()}.
 887      * It will be printed using the format defined below.
 888      * If the offset cannot be obtained then an exception is thrown unless the
 889      * section of the formatter is optional.
 890      * <p>
 891      * When parsing in strict mode, the input must contain the mandatory
 892      * and optional elements are defined by the specified pattern.
 893      * If the offset cannot be parsed then an exception is thrown unless
 894      * the section of the formatter is optional.
 895      * <p>
 896      * When parsing in lenient mode, only the hours are mandatory - minutes
 897      * and seconds are optional. The colons are required if the specified
 898      * pattern contains a colon. If the specified pattern is "+HH", the
 899      * presence of colons is determined by whether the character after the
 900      * hour digits is a colon or not.
 901      * If the offset cannot be parsed then an exception is thrown unless
 902      * the section of the formatter is optional.
 903      * <p>
 904      * The format of the offset is controlled by a pattern which must be one
 905      * of the following:
 906      * <ul>
 907      * <li>{@code +HH} - hour only, ignoring minute and second
 908      * <li>{@code +HHmm} - hour, with minute if non-zero, ignoring second, no colon
 909      * <li>{@code +HH:mm} - hour, with minute if non-zero, ignoring second, with colon
 910      * <li>{@code +HHMM} - hour and minute, ignoring second, no colon
 911      * <li>{@code +HH:MM} - hour and minute, ignoring second, with colon
 912      * <li>{@code +HHMMss} - hour and minute, with second if non-zero, no colon
 913      * <li>{@code +HH:MM:ss} - hour and minute, with second if non-zero, with colon
 914      * <li>{@code +HHMMSS} - hour, minute and second, no colon
 915      * <li>{@code +HH:MM:SS} - hour, minute and second, with colon
 916      * <li>{@code +HHmmss} - hour, with minute if non-zero or with minute and
 917      * second if non-zero, no colon
 918      * <li>{@code +HH:mm:ss} - hour, with minute if non-zero or with minute and
 919      * second if non-zero, with colon
 920      * </ul>
 921      * The "no offset" text controls what text is printed when the total amount of
 922      * the offset fields to be output is zero.
 923      * Example values would be 'Z', '+00:00', 'UTC' or 'GMT'.
 924      * Three formats are accepted for parsing UTC - the "no offset" text, and the
 925      * plus and minus versions of zero defined by the pattern.
 926      *
 927      * @param pattern  the pattern to use, not null
 928      * @param noOffsetText  the text to use when the offset is zero, not null
 929      * @return this, for chaining, not null
 930      * @throws IllegalArgumentException if the pattern is invalid
 931      */
 932     public DateTimeFormatterBuilder appendOffset(String pattern, String noOffsetText) {
 933         appendInternal(new OffsetIdPrinterParser(pattern, noOffsetText));
 934         return this;
 935     }
 936 
 937     /**
 938      * Appends the localized zone offset, such as 'GMT+01:00', to the formatter.
 939      * <p>
 940      * This appends a localized zone offset to the builder, the format of the
 941      * localized offset is controlled by the specified {@link FormatStyle style}
 942      * to this method:
 943      * <ul>
 944      * <li>{@link TextStyle#FULL full} - formats with localized offset text, such
 945      * as 'GMT, 2-digit hour and minute field, optional second field if non-zero,
 946      * and colon.
 947      * <li>{@link TextStyle#SHORT short} - formats with localized offset text,
 948      * such as 'GMT, hour without leading zero, optional 2-digit minute and
 949      * second if non-zero, and colon.
 950      * </ul>
 951      * <p>
 952      * During formatting, the offset is obtained using a mechanism equivalent
 953      * to querying the temporal with {@link TemporalQueries#offset()}.
 954      * If the offset cannot be obtained then an exception is thrown unless the
 955      * section of the formatter is optional.
 956      * <p>
 957      * During parsing, the offset is parsed using the format defined above.
 958      * If the offset cannot be parsed then an exception is thrown unless the
 959      * section of the formatter is optional.
 960      *
 961      * @param style  the format style to use, not null
 962      * @return this, for chaining, not null
 963      * @throws IllegalArgumentException if style is neither {@link TextStyle#FULL
 964      * full} nor {@link TextStyle#SHORT short}
 965      */
 966     public DateTimeFormatterBuilder appendLocalizedOffset(TextStyle style) {
 967         Objects.requireNonNull(style, "style");
 968         if (style != TextStyle.FULL && style != TextStyle.SHORT) {
 969             throw new IllegalArgumentException("Style must be either full or short");
 970         }
 971         appendInternal(new LocalizedOffsetIdPrinterParser(style));
 972         return this;
 973     }
 974 
 975     //-----------------------------------------------------------------------
 976     /**
 977      * Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to the formatter.
 978      * <p>
 979      * This appends an instruction to format/parse the zone ID to the builder.
 980      * The zone ID is obtained in a strict manner suitable for {@code ZonedDateTime}.
 981      * By contrast, {@code OffsetDateTime} does not have a zone ID suitable
 982      * for use with this method, see {@link #appendZoneOrOffsetId()}.
 983      * <p>
 984      * During formatting, the zone is obtained using a mechanism equivalent
 985      * to querying the temporal with {@link TemporalQueries#zoneId()}.
 986      * It will be printed using the result of {@link ZoneId#getId()}.
 987      * If the zone cannot be obtained then an exception is thrown unless the
 988      * section of the formatter is optional.
 989      * <p>
 990      * During parsing, the text must match a known zone or offset.
 991      * There are two types of zone ID, offset-based, such as '+01:30' and
 992      * region-based, such as 'Europe/London'. These are parsed differently.
 993      * If the parse starts with '+', '-', 'UT', 'UTC' or 'GMT', then the parser
 994      * expects an offset-based zone and will not match region-based zones.
 995      * The offset ID, such as '+02:30', may be at the start of the parse,
 996      * or prefixed by  'UT', 'UTC' or 'GMT'. The offset ID parsing is
 997      * equivalent to using {@link #appendOffset(String, String)} using the
 998      * arguments 'HH:MM:ss' and the no offset string '0'.
 999      * If the parse starts with 'UT', 'UTC' or 'GMT', and the parser cannot
1000      * match a following offset ID, then {@link ZoneOffset#UTC} is selected.
1001      * In all other cases, the list of known region-based zones is used to
1002      * find the longest available match. If no match is found, and the parse
1003      * starts with 'Z', then {@code ZoneOffset.UTC} is selected.
1004      * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
1005      * <p>
1006      * For example, the following will parse:
1007      * <pre>
1008      *   "Europe/London"           -- ZoneId.of("Europe/London")
1009      *   "Z"                       -- ZoneOffset.UTC
1010      *   "UT"                      -- ZoneId.of("UT")
1011      *   "UTC"                     -- ZoneId.of("UTC")
1012      *   "GMT"                     -- ZoneId.of("GMT")
1013      *   "+01:30"                  -- ZoneOffset.of("+01:30")
1014      *   "UT+01:30"                -- ZoneOffset.of("+01:30")
1015      *   "UTC+01:30"               -- ZoneOffset.of("+01:30")
1016      *   "GMT+01:30"               -- ZoneOffset.of("+01:30")
1017      * </pre>
1018      *
1019      * @return this, for chaining, not null
1020      * @see #appendZoneRegionId()
1021      */
1022     public DateTimeFormatterBuilder appendZoneId() {
1023         appendInternal(new ZoneIdPrinterParser(TemporalQueries.zoneId(), "ZoneId()"));
1024         return this;
1025     }
1026 
1027     /**
1028      * Appends the time-zone region ID, such as 'Europe/Paris', to the formatter,
1029      * rejecting the zone ID if it is a {@code ZoneOffset}.
1030      * <p>
1031      * This appends an instruction to format/parse the zone ID to the builder
1032      * only if it is a region-based ID.
1033      * <p>
1034      * During formatting, the zone is obtained using a mechanism equivalent
1035      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1036      * If the zone is a {@code ZoneOffset} or it cannot be obtained then
1037      * an exception is thrown unless the section of the formatter is optional.
1038      * If the zone is not an offset, then the zone will be printed using
1039      * the zone ID from {@link ZoneId#getId()}.
1040      * <p>
1041      * During parsing, the text must match a known zone or offset.
1042      * There are two types of zone ID, offset-based, such as '+01:30' and
1043      * region-based, such as 'Europe/London'. These are parsed differently.
1044      * If the parse starts with '+', '-', 'UT', 'UTC' or 'GMT', then the parser
1045      * expects an offset-based zone and will not match region-based zones.
1046      * The offset ID, such as '+02:30', may be at the start of the parse,
1047      * or prefixed by  'UT', 'UTC' or 'GMT'. The offset ID parsing is
1048      * equivalent to using {@link #appendOffset(String, String)} using the
1049      * arguments 'HH:MM:ss' and the no offset string '0'.
1050      * If the parse starts with 'UT', 'UTC' or 'GMT', and the parser cannot
1051      * match a following offset ID, then {@link ZoneOffset#UTC} is selected.
1052      * In all other cases, the list of known region-based zones is used to
1053      * find the longest available match. If no match is found, and the parse
1054      * starts with 'Z', then {@code ZoneOffset.UTC} is selected.
1055      * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
1056      * <p>
1057      * For example, the following will parse:
1058      * <pre>
1059      *   "Europe/London"           -- ZoneId.of("Europe/London")
1060      *   "Z"                       -- ZoneOffset.UTC
1061      *   "UT"                      -- ZoneId.of("UT")
1062      *   "UTC"                     -- ZoneId.of("UTC")
1063      *   "GMT"                     -- ZoneId.of("GMT")
1064      *   "+01:30"                  -- ZoneOffset.of("+01:30")
1065      *   "UT+01:30"                -- ZoneOffset.of("+01:30")
1066      *   "UTC+01:30"               -- ZoneOffset.of("+01:30")
1067      *   "GMT+01:30"               -- ZoneOffset.of("+01:30")
1068      * </pre>
1069      * <p>
1070      * Note that this method is identical to {@code appendZoneId()} except
1071      * in the mechanism used to obtain the zone.
1072      * Note also that parsing accepts offsets, whereas formatting will never
1073      * produce one.
1074      *
1075      * @return this, for chaining, not null
1076      * @see #appendZoneId()
1077      */
1078     public DateTimeFormatterBuilder appendZoneRegionId() {
1079         appendInternal(new ZoneIdPrinterParser(QUERY_REGION_ONLY, "ZoneRegionId()"));
1080         return this;
1081     }
1082 
1083     /**
1084      * Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to
1085      * the formatter, using the best available zone ID.
1086      * <p>
1087      * This appends an instruction to format/parse the best available
1088      * zone or offset ID to the builder.
1089      * The zone ID is obtained in a lenient manner that first attempts to
1090      * find a true zone ID, such as that on {@code ZonedDateTime}, and
1091      * then attempts to find an offset, such as that on {@code OffsetDateTime}.
1092      * <p>
1093      * During formatting, the zone is obtained using a mechanism equivalent
1094      * to querying the temporal with {@link TemporalQueries#zone()}.
1095      * It will be printed using the result of {@link ZoneId#getId()}.
1096      * If the zone cannot be obtained then an exception is thrown unless the
1097      * section of the formatter is optional.
1098      * <p>
1099      * During parsing, the text must match a known zone or offset.
1100      * There are two types of zone ID, offset-based, such as '+01:30' and
1101      * region-based, such as 'Europe/London'. These are parsed differently.
1102      * If the parse starts with '+', '-', 'UT', 'UTC' or 'GMT', then the parser
1103      * expects an offset-based zone and will not match region-based zones.
1104      * The offset ID, such as '+02:30', may be at the start of the parse,
1105      * or prefixed by  'UT', 'UTC' or 'GMT'. The offset ID parsing is
1106      * equivalent to using {@link #appendOffset(String, String)} using the
1107      * arguments 'HH:MM:ss' and the no offset string '0'.
1108      * If the parse starts with 'UT', 'UTC' or 'GMT', and the parser cannot
1109      * match a following offset ID, then {@link ZoneOffset#UTC} is selected.
1110      * In all other cases, the list of known region-based zones is used to
1111      * find the longest available match. If no match is found, and the parse
1112      * starts with 'Z', then {@code ZoneOffset.UTC} is selected.
1113      * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
1114      * <p>
1115      * For example, the following will parse:
1116      * <pre>
1117      *   "Europe/London"           -- ZoneId.of("Europe/London")
1118      *   "Z"                       -- ZoneOffset.UTC
1119      *   "UT"                      -- ZoneId.of("UT")
1120      *   "UTC"                     -- ZoneId.of("UTC")
1121      *   "GMT"                     -- ZoneId.of("GMT")
1122      *   "+01:30"                  -- ZoneOffset.of("+01:30")
1123      *   "UT+01:30"                -- ZoneOffset.of("UT+01:30")
1124      *   "UTC+01:30"               -- ZoneOffset.of("UTC+01:30")
1125      *   "GMT+01:30"               -- ZoneOffset.of("GMT+01:30")
1126      * </pre>
1127      * <p>
1128      * Note that this method is identical to {@code appendZoneId()} except
1129      * in the mechanism used to obtain the zone.
1130      *
1131      * @return this, for chaining, not null
1132      * @see #appendZoneId()
1133      */
1134     public DateTimeFormatterBuilder appendZoneOrOffsetId() {
1135         appendInternal(new ZoneIdPrinterParser(TemporalQueries.zone(), "ZoneOrOffsetId()"));
1136         return this;
1137     }
1138 
1139     /**
1140      * Appends the time-zone name, such as 'British Summer Time', to the formatter.
1141      * <p>
1142      * This appends an instruction to format/parse the textual name of the zone to
1143      * the builder.
1144      * <p>
1145      * During formatting, the zone is obtained using a mechanism equivalent
1146      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1147      * If the zone is a {@code ZoneOffset} it will be printed using the
1148      * result of {@link ZoneOffset#getId()}.
1149      * If the zone is not an offset, the textual name will be looked up
1150      * for the locale set in the {@link DateTimeFormatter}.
1151      * If the temporal object being printed represents an instant, then the text
1152      * will be the summer or winter time text as appropriate.
1153      * If the lookup for text does not find any suitable result, then the
1154      * {@link ZoneId#getId() ID} will be printed instead.
1155      * If the zone cannot be obtained then an exception is thrown unless the
1156      * section of the formatter is optional.
1157      * <p>
1158      * During parsing, either the textual zone name, the zone ID or the offset
1159      * is accepted. Many textual zone names are not unique, such as CST can be
1160      * for both "Central Standard Time" and "China Standard Time". In this
1161      * situation, the zone id will be determined by the region information from
1162      * formatter's  {@link DateTimeFormatter#getLocale() locale} and the standard
1163      * zone id for that area, for example, America/New_York for the America Eastern
1164      * zone. The {@link #appendZoneText(TextStyle, Set)} may be used
1165      * to specify a set of preferred {@link ZoneId} in this situation.
1166      *
1167      * @param textStyle  the text style to use, not null
1168      * @return this, for chaining, not null
1169      */
1170     public DateTimeFormatterBuilder appendZoneText(TextStyle textStyle) {
1171         appendInternal(new ZoneTextPrinterParser(textStyle, null));
1172         return this;
1173     }
1174 
1175     /**
1176      * Appends the time-zone name, such as 'British Summer Time', to the formatter.
1177      * <p>
1178      * This appends an instruction to format/parse the textual name of the zone to
1179      * the builder.
1180      * <p>
1181      * During formatting, the zone is obtained using a mechanism equivalent
1182      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1183      * If the zone is a {@code ZoneOffset} it will be printed using the
1184      * result of {@link ZoneOffset#getId()}.
1185      * If the zone is not an offset, the textual name will be looked up
1186      * for the locale set in the {@link DateTimeFormatter}.
1187      * If the temporal object being printed represents an instant, then the text
1188      * will be the summer or winter time text as appropriate.
1189      * If the lookup for text does not find any suitable result, then the
1190      * {@link ZoneId#getId() ID} will be printed instead.
1191      * If the zone cannot be obtained then an exception is thrown unless the
1192      * section of the formatter is optional.
1193      * <p>
1194      * During parsing, either the textual zone name, the zone ID or the offset
1195      * is accepted. Many textual zone names are not unique, such as CST can be
1196      * for both "Central Standard Time" and "China Standard Time". In this
1197      * situation, the zone id will be determined by the region information from
1198      * formatter's  {@link DateTimeFormatter#getLocale() locale} and the standard
1199      * zone id for that area, for example, America/New_York for the America Eastern
1200      * zone. This method also allows a set of preferred {@link ZoneId} to be
1201      * specified for parsing. The matched preferred zone id will be used if the
1202      * textural zone name being parsed is not unique.
1203      * <p>
1204      * If the zone cannot be parsed then an exception is thrown unless the
1205      * section of the formatter is optional.
1206      *
1207      * @param textStyle  the text style to use, not null
1208      * @param preferredZones  the set of preferred zone ids, not null
1209      * @return this, for chaining, not null
1210      */
1211     public DateTimeFormatterBuilder appendZoneText(TextStyle textStyle,
1212                                                    Set<ZoneId> preferredZones) {
1213         Objects.requireNonNull(preferredZones, "preferredZones");
1214         appendInternal(new ZoneTextPrinterParser(textStyle, preferredZones));
1215         return this;
1216     }
1217 
1218     //-----------------------------------------------------------------------
1219     /**
1220      * Appends the chronology ID, such as 'ISO' or 'ThaiBuddhist', to the formatter.
1221      * <p>
1222      * This appends an instruction to format/parse the chronology ID to the builder.
1223      * <p>
1224      * During formatting, the chronology is obtained using a mechanism equivalent
1225      * to querying the temporal with {@link TemporalQueries#chronology()}.
1226      * It will be printed using the result of {@link Chronology#getId()}.
1227      * If the chronology cannot be obtained then an exception is thrown unless the
1228      * section of the formatter is optional.
1229      * <p>
1230      * During parsing, the chronology is parsed and must match one of the chronologies
1231      * in {@link Chronology#getAvailableChronologies()}.
1232      * If the chronology cannot be parsed then an exception is thrown unless the
1233      * section of the formatter is optional.
1234      * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
1235      *
1236      * @return this, for chaining, not null
1237      */
1238     public DateTimeFormatterBuilder appendChronologyId() {
1239         appendInternal(new ChronoPrinterParser(null));
1240         return this;
1241     }
1242 
1243     /**
1244      * Appends the chronology name to the formatter.
1245      * <p>
1246      * The calendar system name will be output during a format.
1247      * If the chronology cannot be obtained then an exception will be thrown.
1248      *
1249      * @param textStyle  the text style to use, not null
1250      * @return this, for chaining, not null
1251      */
1252     public DateTimeFormatterBuilder appendChronologyText(TextStyle textStyle) {
1253         Objects.requireNonNull(textStyle, "textStyle");
1254         appendInternal(new ChronoPrinterParser(textStyle));
1255         return this;
1256     }
1257 
1258     //-----------------------------------------------------------------------
1259     /**
1260      * Appends a localized date-time pattern to the formatter.
1261      * <p>
1262      * This appends a localized section to the builder, suitable for outputting
1263      * a date, time or date-time combination. The format of the localized
1264      * section is lazily looked up based on four items:
1265      * <ul>
1266      * <li>the {@code dateStyle} specified to this method
1267      * <li>the {@code timeStyle} specified to this method
1268      * <li>the {@code Locale} of the {@code DateTimeFormatter}
1269      * <li>the {@code Chronology}, selecting the best available
1270      * </ul>
1271      * During formatting, the chronology is obtained from the temporal object
1272      * being formatted, which may have been overridden by
1273      * {@link DateTimeFormatter#withChronology(Chronology)}.
1274      * The {@code FULL} and {@code LONG} styles typically require a time-zone.
1275      * When formatting using these styles, a {@code ZoneId} must be available,
1276      * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}.
1277      * <p>
1278      * During parsing, if a chronology has already been parsed, then it is used.
1279      * Otherwise the default from {@code DateTimeFormatter.withChronology(Chronology)}
1280      * is used, with {@code IsoChronology} as the fallback.
1281      * <p>
1282      * Note that this method provides similar functionality to methods on
1283      * {@code DateFormat} such as {@link java.text.DateFormat#getDateTimeInstance(int, int)}.
1284      *
1285      * @param dateStyle  the date style to use, null means no date required
1286      * @param timeStyle  the time style to use, null means no time required
1287      * @return this, for chaining, not null
1288      * @throws IllegalArgumentException if both the date and time styles are null
1289      */
1290     public DateTimeFormatterBuilder appendLocalized(FormatStyle dateStyle, FormatStyle timeStyle) {
1291         if (dateStyle == null && timeStyle == null) {
1292             throw new IllegalArgumentException("Either the date or time style must be non-null");
1293         }
1294         appendInternal(new LocalizedPrinterParser(dateStyle, timeStyle));
1295         return this;
1296     }
1297 
1298     //-----------------------------------------------------------------------
1299     /**
1300      * Appends a character literal to the formatter.
1301      * <p>
1302      * This character will be output during a format.
1303      *
1304      * @param literal  the literal to append, not null
1305      * @return this, for chaining, not null
1306      */
1307     public DateTimeFormatterBuilder appendLiteral(char literal) {
1308         appendInternal(new CharLiteralPrinterParser(literal));
1309         return this;
1310     }
1311 
1312     /**
1313      * Appends a string literal to the formatter.
1314      * <p>
1315      * This string will be output during a format.
1316      * <p>
1317      * If the literal is empty, nothing is added to the formatter.
1318      *
1319      * @param literal  the literal to append, not null
1320      * @return this, for chaining, not null
1321      */
1322     public DateTimeFormatterBuilder appendLiteral(String literal) {
1323         Objects.requireNonNull(literal, "literal");
1324         if (literal.length() > 0) {
1325             if (literal.length() == 1) {
1326                 appendInternal(new CharLiteralPrinterParser(literal.charAt(0)));
1327             } else {
1328                 appendInternal(new StringLiteralPrinterParser(literal));
1329             }
1330         }
1331         return this;
1332     }
1333 
1334     //-----------------------------------------------------------------------
1335     /**
1336      * Appends all the elements of a formatter to the builder.
1337      * <p>
1338      * This method has the same effect as appending each of the constituent
1339      * parts of the formatter directly to this builder.
1340      *
1341      * @param formatter  the formatter to add, not null
1342      * @return this, for chaining, not null
1343      */
1344     public DateTimeFormatterBuilder append(DateTimeFormatter formatter) {
1345         Objects.requireNonNull(formatter, "formatter");
1346         appendInternal(formatter.toPrinterParser(false));
1347         return this;
1348     }
1349 
1350     /**
1351      * Appends a formatter to the builder which will optionally format/parse.
1352      * <p>
1353      * This method has the same effect as appending each of the constituent
1354      * parts directly to this builder surrounded by an {@link #optionalStart()} and
1355      * {@link #optionalEnd()}.
1356      * <p>
1357      * The formatter will format if data is available for all the fields contained within it.
1358      * The formatter will parse if the string matches, otherwise no error is returned.
1359      *
1360      * @param formatter  the formatter to add, not null
1361      * @return this, for chaining, not null
1362      */
1363     public DateTimeFormatterBuilder appendOptional(DateTimeFormatter formatter) {
1364         Objects.requireNonNull(formatter, "formatter");
1365         appendInternal(formatter.toPrinterParser(true));
1366         return this;
1367     }
1368 
1369     //-----------------------------------------------------------------------
1370     /**
1371      * Appends the elements defined by the specified pattern to the builder.
1372      * <p>
1373      * All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters.
1374      * The characters '#', '{' and '}' are reserved for future use.
1375      * The characters '[' and ']' indicate optional patterns.
1376      * The following pattern letters are defined:
1377      * <pre>
1378      *  Symbol  Meaning                     Presentation      Examples
1379      *  ------  -------                     ------------      -------
1380      *   G       era                         text              AD; Anno Domini; A
1381      *   u       year                        year              2004; 04
1382      *   y       year-of-era                 year              2004; 04
1383      *   D       day-of-year                 number            189
1384      *   M/L     month-of-year               number/text       7; 07; Jul; July; J
1385      *   d       day-of-month                number            10
1386      *
1387      *   Q/q     quarter-of-year             number/text       3; 03; Q3; 3rd quarter
1388      *   Y       week-based-year             year              1996; 96
1389      *   w       week-of-week-based-year     number            27
1390      *   W       week-of-month               number            4
1391      *   E       day-of-week                 text              Tue; Tuesday; T
1392      *   e/c     localized day-of-week       number/text       2; 02; Tue; Tuesday; T
1393      *   F       week-of-month               number            3
1394      *
1395      *   a       am-pm-of-day                text              PM
1396      *   h       clock-hour-of-am-pm (1-12)  number            12
1397      *   K       hour-of-am-pm (0-11)        number            0
1398      *   k       clock-hour-of-am-pm (1-24)  number            0
1399      *
1400      *   H       hour-of-day (0-23)          number            0
1401      *   m       minute-of-hour              number            30
1402      *   s       second-of-minute            number            55
1403      *   S       fraction-of-second          fraction          978
1404      *   A       milli-of-day                number            1234
1405      *   n       nano-of-second              number            987654321
1406      *   N       nano-of-day                 number            1234000000
1407      *
1408      *   V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
1409      *   z       time-zone name              zone-name         Pacific Standard Time; PST
1410      *   O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
1411      *   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
1412      *   x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15;
1413      *   Z       zone-offset                 offset-Z          +0000; -0800; -08:00;
1414      *
1415      *   p       pad next                    pad modifier      1
1416      *
1417      *   '       escape for text             delimiter
1418      *   ''      single quote                literal           '
1419      *   [       optional section start
1420      *   ]       optional section end
1421      *   #       reserved for future use
1422      *   {       reserved for future use
1423      *   }       reserved for future use
1424      * </pre>
1425      * <p>
1426      * The count of pattern letters determine the format.
1427      * See <a href="DateTimeFormatter.html#patterns">DateTimeFormatter</a> for a user-focused description of the patterns.
1428      * The following tables define how the pattern letters map to the builder.
1429      * <p>
1430      * <b>Date fields</b>: Pattern letters to output a date.
1431      * <pre>
1432      *  Pattern  Count  Equivalent builder methods
1433      *  -------  -----  --------------------------
1434      *    G       1      appendText(ChronoField.ERA, TextStyle.SHORT)
1435      *    GG      2      appendText(ChronoField.ERA, TextStyle.SHORT)
1436      *    GGG     3      appendText(ChronoField.ERA, TextStyle.SHORT)
1437      *    GGGG    4      appendText(ChronoField.ERA, TextStyle.FULL)
1438      *    GGGGG   5      appendText(ChronoField.ERA, TextStyle.NARROW)
1439      *
1440      *    u       1      appendValue(ChronoField.YEAR, 1, 19, SignStyle.NORMAL);
1441      *    uu      2      appendValueReduced(ChronoField.YEAR, 2, 2000);
1442      *    uuu     3      appendValue(ChronoField.YEAR, 3, 19, SignStyle.NORMAL);
1443      *    u..u    4..n   appendValue(ChronoField.YEAR, n, 19, SignStyle.EXCEEDS_PAD);
1444      *    y       1      appendValue(ChronoField.YEAR_OF_ERA, 1, 19, SignStyle.NORMAL);
1445      *    yy      2      appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2000);
1446      *    yyy     3      appendValue(ChronoField.YEAR_OF_ERA, 3, 19, SignStyle.NORMAL);
1447      *    y..y    4..n   appendValue(ChronoField.YEAR_OF_ERA, n, 19, SignStyle.EXCEEDS_PAD);
1448      *    Y       1      append special localized WeekFields element for numeric week-based-year
1449      *    YY      2      append special localized WeekFields element for reduced numeric week-based-year 2 digits;
1450      *    YYY     3      append special localized WeekFields element for numeric week-based-year (3, 19, SignStyle.NORMAL);
1451      *    Y..Y    4..n   append special localized WeekFields element for numeric week-based-year (n, 19, SignStyle.EXCEEDS_PAD);
1452      *
1453      *    Q       1      appendValue(IsoFields.QUARTER_OF_YEAR);
1454      *    QQ      2      appendValue(IsoFields.QUARTER_OF_YEAR, 2);
1455      *    QQQ     3      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.SHORT)
1456      *    QQQQ    4      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.FULL)
1457      *    QQQQQ   5      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.NARROW)
1458      *    q       1      appendValue(IsoFields.QUARTER_OF_YEAR);
1459      *    qq      2      appendValue(IsoFields.QUARTER_OF_YEAR, 2);
1460      *    qqq     3      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.SHORT_STANDALONE)
1461      *    qqqq    4      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.FULL_STANDALONE)
1462      *    qqqqq   5      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.NARROW_STANDALONE)
1463      *
1464      *    M       1      appendValue(ChronoField.MONTH_OF_YEAR);
1465      *    MM      2      appendValue(ChronoField.MONTH_OF_YEAR, 2);
1466      *    MMM     3      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT)
1467      *    MMMM    4      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.FULL)
1468      *    MMMMM   5      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.NARROW)
1469      *    L       1      appendValue(ChronoField.MONTH_OF_YEAR);
1470      *    LL      2      appendValue(ChronoField.MONTH_OF_YEAR, 2);
1471      *    LLL     3      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT_STANDALONE)
1472      *    LLLL    4      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.FULL_STANDALONE)
1473      *    LLLLL   5      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.NARROW_STANDALONE)
1474      *
1475      *    w       1      append special localized WeekFields element for numeric week-of-year
1476      *    ww      2      append special localized WeekFields element for numeric week-of-year, zero-padded
1477      *    W       1      append special localized WeekFields element for numeric week-of-month
1478      *    d       1      appendValue(ChronoField.DAY_OF_MONTH)
1479      *    dd      2      appendValue(ChronoField.DAY_OF_MONTH, 2)
1480      *    D       1      appendValue(ChronoField.DAY_OF_YEAR)
1481      *    DD      2      appendValue(ChronoField.DAY_OF_YEAR, 2)
1482      *    DDD     3      appendValue(ChronoField.DAY_OF_YEAR, 3)
1483      *    F       1      appendValue(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)
1484      *    E       1      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
1485      *    EE      2      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
1486      *    EEE     3      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
1487      *    EEEE    4      appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL)
1488      *    EEEEE   5      appendText(ChronoField.DAY_OF_WEEK, TextStyle.NARROW)
1489      *    e       1      append special localized WeekFields element for numeric day-of-week
1490      *    ee      2      append special localized WeekFields element for numeric day-of-week, zero-padded
1491      *    eee     3      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
1492      *    eeee    4      appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL)
1493      *    eeeee   5      appendText(ChronoField.DAY_OF_WEEK, TextStyle.NARROW)
1494      *    c       1      append special localized WeekFields element for numeric day-of-week
1495      *    ccc     3      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT_STANDALONE)
1496      *    cccc    4      appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL_STANDALONE)
1497      *    ccccc   5      appendText(ChronoField.DAY_OF_WEEK, TextStyle.NARROW_STANDALONE)
1498      * </pre>
1499      * <p>
1500      * <b>Time fields</b>: Pattern letters to output a time.
1501      * <pre>
1502      *  Pattern  Count  Equivalent builder methods
1503      *  -------  -----  --------------------------
1504      *    a       1      appendText(ChronoField.AMPM_OF_DAY, TextStyle.SHORT)
1505      *    h       1      appendValue(ChronoField.CLOCK_HOUR_OF_AMPM)
1506      *    hh      2      appendValue(ChronoField.CLOCK_HOUR_OF_AMPM, 2)
1507      *    H       1      appendValue(ChronoField.HOUR_OF_DAY)
1508      *    HH      2      appendValue(ChronoField.HOUR_OF_DAY, 2)
1509      *    k       1      appendValue(ChronoField.CLOCK_HOUR_OF_DAY)
1510      *    kk      2      appendValue(ChronoField.CLOCK_HOUR_OF_DAY, 2)
1511      *    K       1      appendValue(ChronoField.HOUR_OF_AMPM)
1512      *    KK      2      appendValue(ChronoField.HOUR_OF_AMPM, 2)
1513      *    m       1      appendValue(ChronoField.MINUTE_OF_HOUR)
1514      *    mm      2      appendValue(ChronoField.MINUTE_OF_HOUR, 2)
1515      *    s       1      appendValue(ChronoField.SECOND_OF_MINUTE)
1516      *    ss      2      appendValue(ChronoField.SECOND_OF_MINUTE, 2)
1517      *
1518      *    S..S    1..n   appendFraction(ChronoField.NANO_OF_SECOND, n, n, false)
1519      *    A       1      appendValue(ChronoField.MILLI_OF_DAY)
1520      *    A..A    2..n   appendValue(ChronoField.MILLI_OF_DAY, n)
1521      *    n       1      appendValue(ChronoField.NANO_OF_SECOND)
1522      *    n..n    2..n   appendValue(ChronoField.NANO_OF_SECOND, n)
1523      *    N       1      appendValue(ChronoField.NANO_OF_DAY)
1524      *    N..N    2..n   appendValue(ChronoField.NANO_OF_DAY, n)
1525      * </pre>
1526      * <p>
1527      * <b>Zone ID</b>: Pattern letters to output {@code ZoneId}.
1528      * <pre>
1529      *  Pattern  Count  Equivalent builder methods
1530      *  -------  -----  --------------------------
1531      *    VV      2      appendZoneId()
1532      *    z       1      appendZoneText(TextStyle.SHORT)
1533      *    zz      2      appendZoneText(TextStyle.SHORT)
1534      *    zzz     3      appendZoneText(TextStyle.SHORT)
1535      *    zzzz    4      appendZoneText(TextStyle.FULL)
1536      * </pre>
1537      * <p>
1538      * <b>Zone offset</b>: Pattern letters to output {@code ZoneOffset}.
1539      * <pre>
1540      *  Pattern  Count  Equivalent builder methods
1541      *  -------  -----  --------------------------
1542      *    O       1      appendLocalizedOffsetPrefixed(TextStyle.SHORT);
1543      *    OOOO    4      appendLocalizedOffsetPrefixed(TextStyle.FULL);
1544      *    X       1      appendOffset("+HHmm","Z")
1545      *    XX      2      appendOffset("+HHMM","Z")
1546      *    XXX     3      appendOffset("+HH:MM","Z")
1547      *    XXXX    4      appendOffset("+HHMMss","Z")
1548      *    XXXXX   5      appendOffset("+HH:MM:ss","Z")
1549      *    x       1      appendOffset("+HHmm","+00")
1550      *    xx      2      appendOffset("+HHMM","+0000")
1551      *    xxx     3      appendOffset("+HH:MM","+00:00")
1552      *    xxxx    4      appendOffset("+HHMMss","+0000")
1553      *    xxxxx   5      appendOffset("+HH:MM:ss","+00:00")
1554      *    Z       1      appendOffset("+HHMM","+0000")
1555      *    ZZ      2      appendOffset("+HHMM","+0000")
1556      *    ZZZ     3      appendOffset("+HHMM","+0000")
1557      *    ZZZZ    4      appendLocalizedOffset(TextStyle.FULL);
1558      *    ZZZZZ   5      appendOffset("+HH:MM:ss","Z")
1559      * </pre>
1560      * <p>
1561      * <b>Modifiers</b>: Pattern letters that modify the rest of the pattern:
1562      * <pre>
1563      *  Pattern  Count  Equivalent builder methods
1564      *  -------  -----  --------------------------
1565      *    [       1      optionalStart()
1566      *    ]       1      optionalEnd()
1567      *    p..p    1..n   padNext(n)
1568      * </pre>
1569      * <p>
1570      * Any sequence of letters not specified above, unrecognized letter or
1571      * reserved character will throw an exception.
1572      * Future versions may add to the set of patterns.
1573      * It is recommended to use single quotes around all characters that you want
1574      * to output directly to ensure that future changes do not break your application.
1575      * <p>
1576      * Note that the pattern string is similar, but not identical, to
1577      * {@link java.text.SimpleDateFormat SimpleDateFormat}.
1578      * The pattern string is also similar, but not identical, to that defined by the
1579      * Unicode Common Locale Data Repository (CLDR/LDML).
1580      * Pattern letters 'X' and 'u' are aligned with Unicode CLDR/LDML.
1581      * By contrast, {@code SimpleDateFormat} uses 'u' for the numeric day of week.
1582      * Pattern letters 'y' and 'Y' parse years of two digits and more than 4 digits differently.
1583      * Pattern letters 'n', 'A', 'N', and 'p' are added.
1584      * Number types will reject large numbers.
1585      *
1586      * @param pattern  the pattern to add, not null
1587      * @return this, for chaining, not null
1588      * @throws IllegalArgumentException if the pattern is invalid
1589      */
1590     public DateTimeFormatterBuilder appendPattern(String pattern) {
1591         Objects.requireNonNull(pattern, "pattern");
1592         parsePattern(pattern);
1593         return this;
1594     }
1595 
1596     private void parsePattern(String pattern) {
1597         for (int pos = 0; pos < pattern.length(); pos++) {
1598             char cur = pattern.charAt(pos);
1599             if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) {
1600                 int start = pos++;
1601                 for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++);  // short loop
1602                 int count = pos - start;
1603                 // padding
1604                 if (cur == 'p') {
1605                     int pad = 0;
1606                     if (pos < pattern.length()) {
1607                         cur = pattern.charAt(pos);
1608                         if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) {
1609                             pad = count;
1610                             start = pos++;
1611                             for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++);  // short loop
1612                             count = pos - start;
1613                         }
1614                     }
1615                     if (pad == 0) {
1616                         throw new IllegalArgumentException(
1617                                 "Pad letter 'p' must be followed by valid pad pattern: " + pattern);
1618                     }
1619                     padNext(pad); // pad and continue parsing
1620                 }
1621                 // main rules
1622                 TemporalField field = FIELD_MAP.get(cur);
1623                 if (field != null) {
1624                     parseField(cur, count, field);
1625                 } else if (cur == 'z') {
1626                     if (count > 4) {
1627                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1628                     } else if (count == 4) {
1629                         appendZoneText(TextStyle.FULL);
1630                     } else {
1631                         appendZoneText(TextStyle.SHORT);
1632                     }
1633                 } else if (cur == 'V') {
1634                     if (count != 2) {
1635                         throw new IllegalArgumentException("Pattern letter count must be 2: " + cur);
1636                     }
1637                     appendZoneId();
1638                 } else if (cur == 'Z') {
1639                     if (count < 4) {
1640                         appendOffset("+HHMM", "+0000");
1641                     } else if (count == 4) {
1642                         appendLocalizedOffset(TextStyle.FULL);
1643                     } else if (count == 5) {
1644                         appendOffset("+HH:MM:ss","Z");
1645                     } else {
1646                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1647                     }
1648                 } else if (cur == 'O') {
1649                     if (count == 1) {
1650                         appendLocalizedOffset(TextStyle.SHORT);
1651                     } else if (count == 4) {
1652                         appendLocalizedOffset(TextStyle.FULL);
1653                     } else {
1654                         throw new IllegalArgumentException("Pattern letter count must be 1 or 4: " + cur);
1655                     }
1656                 } else if (cur == 'X') {
1657                     if (count > 5) {
1658                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1659                     }
1660                     appendOffset(OffsetIdPrinterParser.PATTERNS[count + (count == 1 ? 0 : 1)], "Z");
1661                 } else if (cur == 'x') {
1662                     if (count > 5) {
1663                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1664                     }
1665                     String zero = (count == 1 ? "+00" : (count % 2 == 0 ? "+0000" : "+00:00"));
1666                     appendOffset(OffsetIdPrinterParser.PATTERNS[count + (count == 1 ? 0 : 1)], zero);
1667                 } else if (cur == 'W') {
1668                     // Fields defined by Locale
1669                     if (count > 1) {
1670                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1671                     }
1672                     appendInternal(new WeekBasedFieldPrinterParser(cur, count));
1673                 } else if (cur == 'w') {
1674                     // Fields defined by Locale
1675                     if (count > 2) {
1676                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1677                     }
1678                     appendInternal(new WeekBasedFieldPrinterParser(cur, count));
1679                 } else if (cur == 'Y') {
1680                     // Fields defined by Locale
1681                     appendInternal(new WeekBasedFieldPrinterParser(cur, count));
1682                 } else {
1683                     throw new IllegalArgumentException("Unknown pattern letter: " + cur);
1684                 }
1685                 pos--;
1686 
1687             } else if (cur == '\'') {
1688                 // parse literals
1689                 int start = pos++;
1690                 for ( ; pos < pattern.length(); pos++) {
1691                     if (pattern.charAt(pos) == '\'') {
1692                         if (pos + 1 < pattern.length() && pattern.charAt(pos + 1) == '\'') {
1693                             pos++;
1694                         } else {
1695                             break;  // end of literal
1696                         }
1697                     }
1698                 }
1699                 if (pos >= pattern.length()) {
1700                     throw new IllegalArgumentException("Pattern ends with an incomplete string literal: " + pattern);
1701                 }
1702                 String str = pattern.substring(start + 1, pos);
1703                 if (str.length() == 0) {
1704                     appendLiteral('\'');
1705                 } else {
1706                     appendLiteral(str.replace("''", "'"));
1707                 }
1708 
1709             } else if (cur == '[') {
1710                 optionalStart();
1711 
1712             } else if (cur == ']') {
1713                 if (active.parent == null) {
1714                     throw new IllegalArgumentException("Pattern invalid as it contains ] without previous [");
1715                 }
1716                 optionalEnd();
1717 
1718             } else if (cur == '{' || cur == '}' || cur == '#') {
1719                 throw new IllegalArgumentException("Pattern includes reserved character: '" + cur + "'");
1720             } else {
1721                 appendLiteral(cur);
1722             }
1723         }
1724     }
1725 
1726     @SuppressWarnings("fallthrough")
1727     private void parseField(char cur, int count, TemporalField field) {
1728         boolean standalone = false;
1729         switch (cur) {
1730             case 'u':
1731             case 'y':
1732                 if (count == 2) {
1733                     appendValueReduced(field, 2, 2, ReducedPrinterParser.BASE_DATE);
1734                 } else if (count < 4) {
1735                     appendValue(field, count, 19, SignStyle.NORMAL);
1736                 } else {
1737                     appendValue(field, count, 19, SignStyle.EXCEEDS_PAD);
1738                 }
1739                 break;
1740             case 'c':
1741                 if (count == 2) {
1742                     throw new IllegalArgumentException("Invalid pattern \"cc\"");
1743                 }
1744                 /*fallthrough*/
1745             case 'L':
1746             case 'q':
1747                 standalone = true;
1748                 /*fallthrough*/
1749             case 'M':
1750             case 'Q':
1751             case 'E':
1752             case 'e':
1753                 switch (count) {
1754                     case 1:
1755                     case 2:
1756                         if (cur == 'c' || cur == 'e') {
1757                             appendInternal(new WeekBasedFieldPrinterParser(cur, count));
1758                         } else if (cur == 'E') {
1759                             appendText(field, TextStyle.SHORT);
1760                         } else {
1761                             if (count == 1) {
1762                                 appendValue(field);
1763                             } else {
1764                                 appendValue(field, 2);
1765                             }
1766                         }
1767                         break;
1768                     case 3:
1769                         appendText(field, standalone ? TextStyle.SHORT_STANDALONE : TextStyle.SHORT);
1770                         break;
1771                     case 4:
1772                         appendText(field, standalone ? TextStyle.FULL_STANDALONE : TextStyle.FULL);
1773                         break;
1774                     case 5:
1775                         appendText(field, standalone ? TextStyle.NARROW_STANDALONE : TextStyle.NARROW);
1776                         break;
1777                     default:
1778                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1779                 }
1780                 break;
1781             case 'a':
1782                 if (count == 1) {
1783                     appendText(field, TextStyle.SHORT);
1784                 } else {
1785                     throw new IllegalArgumentException("Too many pattern letters: " + cur);
1786                 }
1787                 break;
1788             case 'G':
1789                 switch (count) {
1790                     case 1:
1791                     case 2:
1792                     case 3:
1793                         appendText(field, TextStyle.SHORT);
1794                         break;
1795                     case 4:
1796                         appendText(field, TextStyle.FULL);
1797                         break;
1798                     case 5:
1799                         appendText(field, TextStyle.NARROW);
1800                         break;
1801                     default:
1802                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1803                 }
1804                 break;
1805             case 'S':
1806                 appendFraction(NANO_OF_SECOND, count, count, false);
1807                 break;
1808             case 'F':
1809                 if (count == 1) {
1810                     appendValue(field);
1811                 } else {
1812                     throw new IllegalArgumentException("Too many pattern letters: " + cur);
1813                 }
1814                 break;
1815             case 'd':
1816             case 'h':
1817             case 'H':
1818             case 'k':
1819             case 'K':
1820             case 'm':
1821             case 's':
1822                 if (count == 1) {
1823                     appendValue(field);
1824                 } else if (count == 2) {
1825                     appendValue(field, count);
1826                 } else {
1827                     throw new IllegalArgumentException("Too many pattern letters: " + cur);
1828                 }
1829                 break;
1830             case 'D':
1831                 if (count == 1) {
1832                     appendValue(field);
1833                 } else if (count <= 3) {
1834                     appendValue(field, count);
1835                 } else {
1836                     throw new IllegalArgumentException("Too many pattern letters: " + cur);
1837                 }
1838                 break;
1839             default:
1840                 if (count == 1) {
1841                     appendValue(field);
1842                 } else {
1843                     appendValue(field, count);
1844                 }
1845                 break;
1846         }
1847     }
1848 
1849     /** Map of letters to fields. */
1850     private static final Map<Character, TemporalField> FIELD_MAP = new HashMap<>();
1851     static {
1852         // SDF = SimpleDateFormat
1853         FIELD_MAP.put('G', ChronoField.ERA);                       // SDF, LDML (different to both for 1/2 chars)
1854         FIELD_MAP.put('y', ChronoField.YEAR_OF_ERA);               // SDF, LDML
1855         FIELD_MAP.put('u', ChronoField.YEAR);                      // LDML (different in SDF)
1856         FIELD_MAP.put('Q', IsoFields.QUARTER_OF_YEAR);             // LDML (removed quarter from 310)
1857         FIELD_MAP.put('q', IsoFields.QUARTER_OF_YEAR);             // LDML (stand-alone)
1858         FIELD_MAP.put('M', ChronoField.MONTH_OF_YEAR);             // SDF, LDML
1859         FIELD_MAP.put('L', ChronoField.MONTH_OF_YEAR);             // SDF, LDML (stand-alone)
1860         FIELD_MAP.put('D', ChronoField.DAY_OF_YEAR);               // SDF, LDML
1861         FIELD_MAP.put('d', ChronoField.DAY_OF_MONTH);              // SDF, LDML
1862         FIELD_MAP.put('F', ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH);  // SDF, LDML
1863         FIELD_MAP.put('E', ChronoField.DAY_OF_WEEK);               // SDF, LDML (different to both for 1/2 chars)
1864         FIELD_MAP.put('c', ChronoField.DAY_OF_WEEK);               // LDML (stand-alone)
1865         FIELD_MAP.put('e', ChronoField.DAY_OF_WEEK);               // LDML (needs localized week number)
1866         FIELD_MAP.put('a', ChronoField.AMPM_OF_DAY);               // SDF, LDML
1867         FIELD_MAP.put('H', ChronoField.HOUR_OF_DAY);               // SDF, LDML
1868         FIELD_MAP.put('k', ChronoField.CLOCK_HOUR_OF_DAY);         // SDF, LDML
1869         FIELD_MAP.put('K', ChronoField.HOUR_OF_AMPM);              // SDF, LDML
1870         FIELD_MAP.put('h', ChronoField.CLOCK_HOUR_OF_AMPM);        // SDF, LDML
1871         FIELD_MAP.put('m', ChronoField.MINUTE_OF_HOUR);            // SDF, LDML
1872         FIELD_MAP.put('s', ChronoField.SECOND_OF_MINUTE);          // SDF, LDML
1873         FIELD_MAP.put('S', ChronoField.NANO_OF_SECOND);            // LDML (SDF uses milli-of-second number)
1874         FIELD_MAP.put('A', ChronoField.MILLI_OF_DAY);              // LDML
1875         FIELD_MAP.put('n', ChronoField.NANO_OF_SECOND);            // 310 (proposed for LDML)
1876         FIELD_MAP.put('N', ChronoField.NANO_OF_DAY);               // 310 (proposed for LDML)
1877         // 310 - z - time-zone names, matches LDML and SimpleDateFormat 1 to 4
1878         // 310 - Z - matches SimpleDateFormat and LDML
1879         // 310 - V - time-zone id, matches LDML
1880         // 310 - p - prefix for padding
1881         // 310 - X - matches LDML, almost matches SDF for 1, exact match 2&3, extended 4&5
1882         // 310 - x - matches LDML
1883         // 310 - w, W, and Y are localized forms matching LDML
1884         // LDML - U - cycle year name, not supported by 310 yet
1885         // LDML - l - deprecated
1886         // LDML - j - not relevant
1887         // LDML - g - modified-julian-day
1888         // LDML - v,V - extended time-zone names
1889     }
1890 
1891     //-----------------------------------------------------------------------
1892     /**
1893      * Causes the next added printer/parser to pad to a fixed width using a space.
1894      * <p>
1895      * This padding will pad to a fixed width using spaces.
1896      * <p>
1897      * During formatting, the decorated element will be output and then padded
1898      * to the specified width. An exception will be thrown during formatting if
1899      * the pad width is exceeded.
1900      * <p>
1901      * During parsing, the padding and decorated element are parsed.
1902      * If parsing is lenient, then the pad width is treated as a maximum.
1903      * The padding is parsed greedily. Thus, if the decorated element starts with
1904      * the pad character, it will not be parsed.
1905      *
1906      * @param padWidth  the pad width, 1 or greater
1907      * @return this, for chaining, not null
1908      * @throws IllegalArgumentException if pad width is too small
1909      */
1910     public DateTimeFormatterBuilder padNext(int padWidth) {
1911         return padNext(padWidth, ' ');
1912     }
1913 
1914     /**
1915      * Causes the next added printer/parser to pad to a fixed width.
1916      * <p>
1917      * This padding is intended for padding other than zero-padding.
1918      * Zero-padding should be achieved using the appendValue methods.
1919      * <p>
1920      * During formatting, the decorated element will be output and then padded
1921      * to the specified width. An exception will be thrown during formatting if
1922      * the pad width is exceeded.
1923      * <p>
1924      * During parsing, the padding and decorated element are parsed.
1925      * If parsing is lenient, then the pad width is treated as a maximum.
1926      * If parsing is case insensitive, then the pad character is matched ignoring case.
1927      * The padding is parsed greedily. Thus, if the decorated element starts with
1928      * the pad character, it will not be parsed.
1929      *
1930      * @param padWidth  the pad width, 1 or greater
1931      * @param padChar  the pad character
1932      * @return this, for chaining, not null
1933      * @throws IllegalArgumentException if pad width is too small
1934      */
1935     public DateTimeFormatterBuilder padNext(int padWidth, char padChar) {
1936         if (padWidth < 1) {
1937             throw new IllegalArgumentException("The pad width must be at least one but was " + padWidth);
1938         }
1939         active.padNextWidth = padWidth;
1940         active.padNextChar = padChar;
1941         active.valueParserIndex = -1;
1942         return this;
1943     }
1944 
1945     //-----------------------------------------------------------------------
1946     /**
1947      * Mark the start of an optional section.
1948      * <p>
1949      * The output of formatting can include optional sections, which may be nested.
1950      * An optional section is started by calling this method and ended by calling
1951      * {@link #optionalEnd()} or by ending the build process.
1952      * <p>
1953      * All elements in the optional section are treated as optional.
1954      * During formatting, the section is only output if data is available in the
1955      * {@code TemporalAccessor} for all the elements in the section.
1956      * During parsing, the whole section may be missing from the parsed string.
1957      * <p>
1958      * For example, consider a builder setup as
1959      * {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2)}.
1960      * The optional section ends automatically at the end of the builder.
1961      * During formatting, the minute will only be output if its value can be obtained from the date-time.
1962      * During parsing, the input will be successfully parsed whether the minute is present or not.
1963      *
1964      * @return this, for chaining, not null
1965      */
1966     public DateTimeFormatterBuilder optionalStart() {
1967         active.valueParserIndex = -1;
1968         active = new DateTimeFormatterBuilder(active, true);
1969         return this;
1970     }
1971 
1972     /**
1973      * Ends an optional section.
1974      * <p>
1975      * The output of formatting can include optional sections, which may be nested.
1976      * An optional section is started by calling {@link #optionalStart()} and ended
1977      * using this method (or at the end of the builder).
1978      * <p>
1979      * Calling this method without having previously called {@code optionalStart}
1980      * will throw an exception.
1981      * Calling this method immediately after calling {@code optionalStart} has no effect
1982      * on the formatter other than ending the (empty) optional section.
1983      * <p>
1984      * All elements in the optional section are treated as optional.
1985      * During formatting, the section is only output if data is available in the
1986      * {@code TemporalAccessor} for all the elements in the section.
1987      * During parsing, the whole section may be missing from the parsed string.
1988      * <p>
1989      * For example, consider a builder setup as
1990      * {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2).optionalEnd()}.
1991      * During formatting, the minute will only be output if its value can be obtained from the date-time.
1992      * During parsing, the input will be successfully parsed whether the minute is present or not.
1993      *
1994      * @return this, for chaining, not null
1995      * @throws IllegalStateException if there was no previous call to {@code optionalStart}
1996      */
1997     public DateTimeFormatterBuilder optionalEnd() {
1998         if (active.parent == null) {
1999             throw new IllegalStateException("Cannot call optionalEnd() as there was no previous call to optionalStart()");
2000         }
2001         if (active.printerParsers.size() > 0) {
2002             CompositePrinterParser cpp = new CompositePrinterParser(active.printerParsers, active.optional);
2003             active = active.parent;
2004             appendInternal(cpp);
2005         } else {
2006             active = active.parent;
2007         }
2008         return this;
2009     }
2010 
2011     //-----------------------------------------------------------------------
2012     /**
2013      * Appends a printer and/or parser to the internal list handling padding.
2014      *
2015      * @param pp  the printer-parser to add, not null
2016      * @return the index into the active parsers list
2017      */
2018     private int appendInternal(DateTimePrinterParser pp) {
2019         Objects.requireNonNull(pp, "pp");
2020         if (active.padNextWidth > 0) {
2021             if (pp != null) {
2022                 pp = new PadPrinterParserDecorator(pp, active.padNextWidth, active.padNextChar);
2023             }
2024             active.padNextWidth = 0;
2025             active.padNextChar = 0;
2026         }
2027         active.printerParsers.add(pp);
2028         active.valueParserIndex = -1;
2029         return active.printerParsers.size() - 1;
2030     }
2031 
2032     //-----------------------------------------------------------------------
2033     /**
2034      * Completes this builder by creating the {@code DateTimeFormatter}
2035      * using the default locale.
2036      * <p>
2037      * This will create a formatter with the {@linkplain Locale#getDefault(Locale.Category) default FORMAT locale}.
2038      * Numbers will be printed and parsed using the standard DecimalStyle.
2039      * The resolver style will be {@link ResolverStyle#SMART SMART}.
2040      * <p>
2041      * Calling this method will end any open optional sections by repeatedly
2042      * calling {@link #optionalEnd()} before creating the formatter.
2043      * <p>
2044      * This builder can still be used after creating the formatter if desired,
2045      * although the state may have been changed by calls to {@code optionalEnd}.
2046      *
2047      * @return the created formatter, not null
2048      */
2049     public DateTimeFormatter toFormatter() {
2050         return toFormatter(Locale.getDefault(Locale.Category.FORMAT));
2051     }
2052 
2053     /**
2054      * Completes this builder by creating the {@code DateTimeFormatter}
2055      * using the specified locale.
2056      * <p>
2057      * This will create a formatter with the specified locale.
2058      * Numbers will be printed and parsed using the standard DecimalStyle.
2059      * The resolver style will be {@link ResolverStyle#SMART SMART}.
2060      * <p>
2061      * Calling this method will end any open optional sections by repeatedly
2062      * calling {@link #optionalEnd()} before creating the formatter.
2063      * <p>
2064      * This builder can still be used after creating the formatter if desired,
2065      * although the state may have been changed by calls to {@code optionalEnd}.
2066      *
2067      * @param locale  the locale to use for formatting, not null
2068      * @return the created formatter, not null
2069      */
2070     public DateTimeFormatter toFormatter(Locale locale) {
2071         return toFormatter(locale, ResolverStyle.SMART, null);
2072     }
2073 
2074     /**
2075      * Completes this builder by creating the formatter.
2076      * This uses the default locale.
2077      *
2078      * @param resolverStyle  the resolver style to use, not null
2079      * @return the created formatter, not null
2080      */
2081     DateTimeFormatter toFormatter(ResolverStyle resolverStyle, Chronology chrono) {
2082         return toFormatter(Locale.getDefault(Locale.Category.FORMAT), resolverStyle, chrono);
2083     }
2084 
2085     /**
2086      * Completes this builder by creating the formatter.
2087      *
2088      * @param locale  the locale to use for formatting, not null
2089      * @param chrono  the chronology to use, may be null
2090      * @return the created formatter, not null
2091      */
2092     private DateTimeFormatter toFormatter(Locale locale, ResolverStyle resolverStyle, Chronology chrono) {
2093         Objects.requireNonNull(locale, "locale");
2094         while (active.parent != null) {
2095             optionalEnd();
2096         }
2097         CompositePrinterParser pp = new CompositePrinterParser(printerParsers, false);
2098         return new DateTimeFormatter(pp, locale, DecimalStyle.STANDARD,
2099                 resolverStyle, null, chrono, null);
2100     }
2101 
2102     //-----------------------------------------------------------------------
2103     /**
2104      * Strategy for formatting/parsing date-time information.
2105      * <p>
2106      * The printer may format any part, or the whole, of the input date-time object.
2107      * Typically, a complete format is constructed from a number of smaller
2108      * units, each outputting a single field.
2109      * <p>
2110      * The parser may parse any piece of text from the input, storing the result
2111      * in the context. Typically, each individual parser will just parse one
2112      * field, such as the day-of-month, storing the value in the context.
2113      * Once the parse is complete, the caller will then resolve the parsed values
2114      * to create the desired object, such as a {@code LocalDate}.
2115      * <p>
2116      * The parse position will be updated during the parse. Parsing will start at
2117      * the specified index and the return value specifies the new parse position
2118      * for the next parser. If an error occurs, the returned index will be negative
2119      * and will have the error position encoded using the complement operator.
2120      *
2121      * @implSpec
2122      * This interface must be implemented with care to ensure other classes operate correctly.
2123      * All implementations that can be instantiated must be final, immutable and thread-safe.
2124      * <p>
2125      * The context is not a thread-safe object and a new instance will be created
2126      * for each format that occurs. The context must not be stored in an instance
2127      * variable or shared with any other threads.
2128      */
2129     interface DateTimePrinterParser {
2130 
2131         /**
2132          * Prints the date-time object to the buffer.
2133          * <p>
2134          * The context holds information to use during the format.
2135          * It also contains the date-time information to be printed.
2136          * <p>
2137          * The buffer must not be mutated beyond the content controlled by the implementation.
2138          *
2139          * @param context  the context to format using, not null
2140          * @param buf  the buffer to append to, not null
2141          * @return false if unable to query the value from the date-time, true otherwise
2142          * @throws DateTimeException if the date-time cannot be printed successfully
2143          */
2144         boolean format(DateTimePrintContext context, StringBuilder buf);
2145 
2146         /**
2147          * Parses text into date-time information.
2148          * <p>
2149          * The context holds information to use during the parse.
2150          * It is also used to store the parsed date-time information.
2151          *
2152          * @param context  the context to use and parse into, not null
2153          * @param text  the input text to parse, not null
2154          * @param position  the position to start parsing at, from 0 to the text length
2155          * @return the new parse position, where negative means an error with the
2156          *  error position encoded using the complement ~ operator
2157          * @throws NullPointerException if the context or text is null
2158          * @throws IndexOutOfBoundsException if the position is invalid
2159          */
2160         int parse(DateTimeParseContext context, CharSequence text, int position);
2161     }
2162 
2163     //-----------------------------------------------------------------------
2164     /**
2165      * Composite printer and parser.
2166      */
2167     static final class CompositePrinterParser implements DateTimePrinterParser {
2168         private final DateTimePrinterParser[] printerParsers;
2169         private final boolean optional;
2170 
2171         CompositePrinterParser(List<DateTimePrinterParser> printerParsers, boolean optional) {
2172             this(printerParsers.toArray(new DateTimePrinterParser[printerParsers.size()]), optional);
2173         }
2174 
2175         CompositePrinterParser(DateTimePrinterParser[] printerParsers, boolean optional) {
2176             this.printerParsers = printerParsers;
2177             this.optional = optional;
2178         }
2179 
2180         /**
2181          * Returns a copy of this printer-parser with the optional flag changed.
2182          *
2183          * @param optional  the optional flag to set in the copy
2184          * @return the new printer-parser, not null
2185          */
2186         public CompositePrinterParser withOptional(boolean optional) {
2187             if (optional == this.optional) {
2188                 return this;
2189             }
2190             return new CompositePrinterParser(printerParsers, optional);
2191         }
2192 
2193         @Override
2194         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2195             int length = buf.length();
2196             if (optional) {
2197                 context.startOptional();
2198             }
2199             try {
2200                 for (DateTimePrinterParser pp : printerParsers) {
2201                     if (pp.format(context, buf) == false) {
2202                         buf.setLength(length);  // reset buffer
2203                         return true;
2204                     }
2205                 }
2206             } finally {
2207                 if (optional) {
2208                     context.endOptional();
2209                 }
2210             }
2211             return true;
2212         }
2213 
2214         @Override
2215         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2216             if (optional) {
2217                 context.startOptional();
2218                 int pos = position;
2219                 for (DateTimePrinterParser pp : printerParsers) {
2220                     pos = pp.parse(context, text, pos);
2221                     if (pos < 0) {
2222                         context.endOptional(false);
2223                         return position;  // return original position
2224                     }
2225                 }
2226                 context.endOptional(true);
2227                 return pos;
2228             } else {
2229                 for (DateTimePrinterParser pp : printerParsers) {
2230                     position = pp.parse(context, text, position);
2231                     if (position < 0) {
2232                         break;
2233                     }
2234                 }
2235                 return position;
2236             }
2237         }
2238 
2239         @Override
2240         public String toString() {
2241             StringBuilder buf = new StringBuilder();
2242             if (printerParsers != null) {
2243                 buf.append(optional ? "[" : "(");
2244                 for (DateTimePrinterParser pp : printerParsers) {
2245                     buf.append(pp);
2246                 }
2247                 buf.append(optional ? "]" : ")");
2248             }
2249             return buf.toString();
2250         }
2251     }
2252 
2253     //-----------------------------------------------------------------------
2254     /**
2255      * Pads the output to a fixed width.
2256      */
2257     static final class PadPrinterParserDecorator implements DateTimePrinterParser {
2258         private final DateTimePrinterParser printerParser;
2259         private final int padWidth;
2260         private final char padChar;
2261 
2262         /**
2263          * Constructor.
2264          *
2265          * @param printerParser  the printer, not null
2266          * @param padWidth  the width to pad to, 1 or greater
2267          * @param padChar  the pad character
2268          */
2269         PadPrinterParserDecorator(DateTimePrinterParser printerParser, int padWidth, char padChar) {
2270             // input checked by DateTimeFormatterBuilder
2271             this.printerParser = printerParser;
2272             this.padWidth = padWidth;
2273             this.padChar = padChar;
2274         }
2275 
2276         @Override
2277         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2278             int preLen = buf.length();
2279             if (printerParser.format(context, buf) == false) {
2280                 return false;
2281             }
2282             int len = buf.length() - preLen;
2283             if (len > padWidth) {
2284                 throw new DateTimeException(
2285                     "Cannot print as output of " + len + " characters exceeds pad width of " + padWidth);
2286             }
2287             for (int i = 0; i < padWidth - len; i++) {
2288                 buf.insert(preLen, padChar);
2289             }
2290             return true;
2291         }
2292 
2293         @Override
2294         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2295             // cache context before changed by decorated parser
2296             final boolean strict = context.isStrict();
2297             // parse
2298             if (position > text.length()) {
2299                 throw new IndexOutOfBoundsException();
2300             }
2301             if (position == text.length()) {
2302                 return ~position;  // no more characters in the string
2303             }
2304             int endPos = position + padWidth;
2305             if (endPos > text.length()) {
2306                 if (strict) {
2307                     return ~position;  // not enough characters in the string to meet the parse width
2308                 }
2309                 endPos = text.length();
2310             }
2311             int pos = position;
2312             while (pos < endPos && context.charEquals(text.charAt(pos), padChar)) {
2313                 pos++;
2314             }
2315             text = text.subSequence(0, endPos);
2316             int resultPos = printerParser.parse(context, text, pos);
2317             if (resultPos != endPos && strict) {
2318                 return ~(position + pos);  // parse of decorated field didn't parse to the end
2319             }
2320             return resultPos;
2321         }
2322 
2323         @Override
2324         public String toString() {
2325             return "Pad(" + printerParser + "," + padWidth + (padChar == ' ' ? ")" : ",'" + padChar + "')");
2326         }
2327     }
2328 
2329     //-----------------------------------------------------------------------
2330     /**
2331      * Enumeration to apply simple parse settings.
2332      */
2333     static enum SettingsParser implements DateTimePrinterParser {
2334         SENSITIVE,
2335         INSENSITIVE,
2336         STRICT,
2337         LENIENT;
2338 
2339         @Override
2340         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2341             return true;  // nothing to do here
2342         }
2343 
2344         @Override
2345         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2346             // using ordinals to avoid javac synthetic inner class
2347             switch (ordinal()) {
2348                 case 0: context.setCaseSensitive(true); break;
2349                 case 1: context.setCaseSensitive(false); break;
2350                 case 2: context.setStrict(true); break;
2351                 case 3: context.setStrict(false); break;
2352             }
2353             return position;
2354         }
2355 
2356         @Override
2357         public String toString() {
2358             // using ordinals to avoid javac synthetic inner class
2359             switch (ordinal()) {
2360                 case 0: return "ParseCaseSensitive(true)";
2361                 case 1: return "ParseCaseSensitive(false)";
2362                 case 2: return "ParseStrict(true)";
2363                 case 3: return "ParseStrict(false)";
2364             }
2365             throw new IllegalStateException("Unreachable");
2366         }
2367     }
2368 
2369     //-----------------------------------------------------------------------
2370     /**
2371      * Defaults a value into the parse if not currently present.
2372      */
2373     static class DefaultValueParser implements DateTimePrinterParser {
2374         private final TemporalField field;
2375         private final long value;
2376 
2377         DefaultValueParser(TemporalField field, long value) {
2378             this.field = field;
2379             this.value = value;
2380         }
2381 
2382         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2383             return true;
2384         }
2385 
2386         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2387             if (context.getParsed(field) == null) {
2388                 context.setParsedField(field, value, position, position);
2389             }
2390             return position;
2391         }
2392     }
2393 
2394     //-----------------------------------------------------------------------
2395     /**
2396      * Prints or parses a character literal.
2397      */
2398     static final class CharLiteralPrinterParser implements DateTimePrinterParser {
2399         private final char literal;
2400 
2401         CharLiteralPrinterParser(char literal) {
2402             this.literal = literal;
2403         }
2404 
2405         @Override
2406         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2407             buf.append(literal);
2408             return true;
2409         }
2410 
2411         @Override
2412         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2413             int length = text.length();
2414             if (position == length) {
2415                 return ~position;
2416             }
2417             char ch = text.charAt(position);
2418             if (ch != literal) {
2419                 if (context.isCaseSensitive() ||
2420                         (Character.toUpperCase(ch) != Character.toUpperCase(literal) &&
2421                          Character.toLowerCase(ch) != Character.toLowerCase(literal))) {
2422                     return ~position;
2423                 }
2424             }
2425             return position + 1;
2426         }
2427 
2428         @Override
2429         public String toString() {
2430             if (literal == '\'') {
2431                 return "''";
2432             }
2433             return "'" + literal + "'";
2434         }
2435     }
2436 
2437     //-----------------------------------------------------------------------
2438     /**
2439      * Prints or parses a string literal.
2440      */
2441     static final class StringLiteralPrinterParser implements DateTimePrinterParser {
2442         private final String literal;
2443 
2444         StringLiteralPrinterParser(String literal) {
2445             this.literal = literal;  // validated by caller
2446         }
2447 
2448         @Override
2449         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2450             buf.append(literal);
2451             return true;
2452         }
2453 
2454         @Override
2455         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2456             int length = text.length();
2457             if (position > length || position < 0) {
2458                 throw new IndexOutOfBoundsException();
2459             }
2460             if (context.subSequenceEquals(text, position, literal, 0, literal.length()) == false) {
2461                 return ~position;
2462             }
2463             return position + literal.length();
2464         }
2465 
2466         @Override
2467         public String toString() {
2468             String converted = literal.replace("'", "''");
2469             return "'" + converted + "'";
2470         }
2471     }
2472 
2473     //-----------------------------------------------------------------------
2474     /**
2475      * Prints and parses a numeric date-time field with optional padding.
2476      */
2477     static class NumberPrinterParser implements DateTimePrinterParser {
2478 
2479         /**
2480          * Array of 10 to the power of n.
2481          */
2482         static final long[] EXCEED_POINTS = new long[] {
2483             0L,
2484             10L,
2485             100L,
2486             1000L,
2487             10000L,
2488             100000L,
2489             1000000L,
2490             10000000L,
2491             100000000L,
2492             1000000000L,
2493             10000000000L,
2494         };
2495 
2496         final TemporalField field;
2497         final int minWidth;
2498         final int maxWidth;
2499         private final SignStyle signStyle;
2500         final int subsequentWidth;
2501 
2502         /**
2503          * Constructor.
2504          *
2505          * @param field  the field to format, not null
2506          * @param minWidth  the minimum field width, from 1 to 19
2507          * @param maxWidth  the maximum field width, from minWidth to 19
2508          * @param signStyle  the positive/negative sign style, not null
2509          */
2510         NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) {
2511             // validated by caller
2512             this.field = field;
2513             this.minWidth = minWidth;
2514             this.maxWidth = maxWidth;
2515             this.signStyle = signStyle;
2516             this.subsequentWidth = 0;
2517         }
2518 
2519         /**
2520          * Constructor.
2521          *
2522          * @param field  the field to format, not null
2523          * @param minWidth  the minimum field width, from 1 to 19
2524          * @param maxWidth  the maximum field width, from minWidth to 19
2525          * @param signStyle  the positive/negative sign style, not null
2526          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater,
2527          *  -1 if fixed width due to active adjacent parsing
2528          */
2529         protected NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle, int subsequentWidth) {
2530             // validated by caller
2531             this.field = field;
2532             this.minWidth = minWidth;
2533             this.maxWidth = maxWidth;
2534             this.signStyle = signStyle;
2535             this.subsequentWidth = subsequentWidth;
2536         }
2537 
2538         /**
2539          * Returns a new instance with fixed width flag set.
2540          *
2541          * @return a new updated printer-parser, not null
2542          */
2543         NumberPrinterParser withFixedWidth() {
2544             if (subsequentWidth == -1) {
2545                 return this;
2546             }
2547             return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, -1);
2548         }
2549 
2550         /**
2551          * Returns a new instance with an updated subsequent width.
2552          *
2553          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater
2554          * @return a new updated printer-parser, not null
2555          */
2556         NumberPrinterParser withSubsequentWidth(int subsequentWidth) {
2557             return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, this.subsequentWidth + subsequentWidth);
2558         }
2559 
2560         @Override
2561         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2562             Long valueLong = context.getValue(field);
2563             if (valueLong == null) {
2564                 return false;
2565             }
2566             long value = getValue(context, valueLong);
2567             DecimalStyle decimalStyle = context.getDecimalStyle();
2568             String str = (value == Long.MIN_VALUE ? "9223372036854775808" : Long.toString(Math.abs(value)));
2569             if (str.length() > maxWidth) {
2570                 throw new DateTimeException("Field " + field +
2571                     " cannot be printed as the value " + value +
2572                     " exceeds the maximum print width of " + maxWidth);
2573             }
2574             str = decimalStyle.convertNumberToI18N(str);
2575 
2576             if (value >= 0) {
2577                 switch (signStyle) {
2578                     case EXCEEDS_PAD:
2579                         if (minWidth < 19 && value >= EXCEED_POINTS[minWidth]) {
2580                             buf.append(decimalStyle.getPositiveSign());
2581                         }
2582                         break;
2583                     case ALWAYS:
2584                         buf.append(decimalStyle.getPositiveSign());
2585                         break;
2586                 }
2587             } else {
2588                 switch (signStyle) {
2589                     case NORMAL:
2590                     case EXCEEDS_PAD:
2591                     case ALWAYS:
2592                         buf.append(decimalStyle.getNegativeSign());
2593                         break;
2594                     case NOT_NEGATIVE:
2595                         throw new DateTimeException("Field " + field +
2596                             " cannot be printed as the value " + value +
2597                             " cannot be negative according to the SignStyle");
2598                 }
2599             }
2600             for (int i = 0; i < minWidth - str.length(); i++) {
2601                 buf.append(decimalStyle.getZeroDigit());
2602             }
2603             buf.append(str);
2604             return true;
2605         }
2606 
2607         /**
2608          * Gets the value to output.
2609          *
2610          * @param context  the context
2611          * @param value  the value of the field, not null
2612          * @return the value
2613          */
2614         long getValue(DateTimePrintContext context, long value) {
2615             return value;
2616         }
2617 
2618         /**
2619          * For NumberPrinterParser, the width is fixed depending on the
2620          * minWidth, maxWidth, signStyle and whether subsequent fields are fixed.
2621          * @param context the context
2622          * @return true if the field is fixed width
2623          * @see DateTimeFormatterBuilder#appendValue(java.time.temporal.TemporalField, int)
2624          */
2625         boolean isFixedWidth(DateTimeParseContext context) {
2626             return subsequentWidth == -1 ||
2627                 (subsequentWidth > 0 && minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE);
2628         }
2629 
2630         @Override
2631         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2632             int length = text.length();
2633             if (position == length) {
2634                 return ~position;
2635             }
2636             char sign = text.charAt(position);  // IOOBE if invalid position
2637             boolean negative = false;
2638             boolean positive = false;
2639             if (sign == context.getDecimalStyle().getPositiveSign()) {
2640                 if (signStyle.parse(true, context.isStrict(), minWidth == maxWidth) == false) {
2641                     return ~position;
2642                 }
2643                 positive = true;
2644                 position++;
2645             } else if (sign == context.getDecimalStyle().getNegativeSign()) {
2646                 if (signStyle.parse(false, context.isStrict(), minWidth == maxWidth) == false) {
2647                     return ~position;
2648                 }
2649                 negative = true;
2650                 position++;
2651             } else {
2652                 if (signStyle == SignStyle.ALWAYS && context.isStrict()) {
2653                     return ~position;
2654                 }
2655             }
2656             int effMinWidth = (context.isStrict() || isFixedWidth(context) ? minWidth : 1);
2657             int minEndPos = position + effMinWidth;
2658             if (minEndPos > length) {
2659                 return ~position;
2660             }
2661             int effMaxWidth = (context.isStrict() || isFixedWidth(context) ? maxWidth : 9) + Math.max(subsequentWidth, 0);
2662             long total = 0;
2663             BigInteger totalBig = null;
2664             int pos = position;
2665             for (int pass = 0; pass < 2; pass++) {
2666                 int maxEndPos = Math.min(pos + effMaxWidth, length);
2667                 while (pos < maxEndPos) {
2668                     char ch = text.charAt(pos++);
2669                     int digit = context.getDecimalStyle().convertToDigit(ch);
2670                     if (digit < 0) {
2671                         pos--;
2672                         if (pos < minEndPos) {
2673                             return ~position;  // need at least min width digits
2674                         }
2675                         break;
2676                     }
2677                     if ((pos - position) > 18) {
2678                         if (totalBig == null) {
2679                             totalBig = BigInteger.valueOf(total);
2680                         }
2681                         totalBig = totalBig.multiply(BigInteger.TEN).add(BigInteger.valueOf(digit));
2682                     } else {
2683                         total = total * 10 + digit;
2684                     }
2685                 }
2686                 if (subsequentWidth > 0 && pass == 0) {
2687                     // re-parse now we know the correct width
2688                     int parseLen = pos - position;
2689                     effMaxWidth = Math.max(effMinWidth, parseLen - subsequentWidth);
2690                     pos = position;
2691                     total = 0;
2692                     totalBig = null;
2693                 } else {
2694                     break;
2695                 }
2696             }
2697             if (negative) {
2698                 if (totalBig != null) {
2699                     if (totalBig.equals(BigInteger.ZERO) && context.isStrict()) {
2700                         return ~(position - 1);  // minus zero not allowed
2701                     }
2702                     totalBig = totalBig.negate();
2703                 } else {
2704                     if (total == 0 && context.isStrict()) {
2705                         return ~(position - 1);  // minus zero not allowed
2706                     }
2707                     total = -total;
2708                 }
2709             } else if (signStyle == SignStyle.EXCEEDS_PAD && context.isStrict()) {
2710                 int parseLen = pos - position;
2711                 if (positive) {
2712                     if (parseLen <= minWidth) {
2713                         return ~(position - 1);  // '+' only parsed if minWidth exceeded
2714                     }
2715                 } else {
2716                     if (parseLen > minWidth) {
2717                         return ~position;  // '+' must be parsed if minWidth exceeded
2718                     }
2719                 }
2720             }
2721             if (totalBig != null) {
2722                 if (totalBig.bitLength() > 63) {
2723                     // overflow, parse 1 less digit
2724                     totalBig = totalBig.divide(BigInteger.TEN);
2725                     pos--;
2726                 }
2727                 return setValue(context, totalBig.longValue(), position, pos);
2728             }
2729             return setValue(context, total, position, pos);
2730         }
2731 
2732         /**
2733          * Stores the value.
2734          *
2735          * @param context  the context to store into, not null
2736          * @param value  the value
2737          * @param errorPos  the position of the field being parsed
2738          * @param successPos  the position after the field being parsed
2739          * @return the new position
2740          */
2741         int setValue(DateTimeParseContext context, long value, int errorPos, int successPos) {
2742             return context.setParsedField(field, value, errorPos, successPos);
2743         }
2744 
2745         @Override
2746         public String toString() {
2747             if (minWidth == 1 && maxWidth == 19 && signStyle == SignStyle.NORMAL) {
2748                 return "Value(" + field + ")";
2749             }
2750             if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) {
2751                 return "Value(" + field + "," + minWidth + ")";
2752             }
2753             return "Value(" + field + "," + minWidth + "," + maxWidth + "," + signStyle + ")";
2754         }
2755     }
2756 
2757     //-----------------------------------------------------------------------
2758     /**
2759      * Prints and parses a reduced numeric date-time field.
2760      */
2761     static final class ReducedPrinterParser extends NumberPrinterParser {
2762         /**
2763          * The base date for reduced value parsing.
2764          */
2765         static final LocalDate BASE_DATE = LocalDate.of(2000, 1, 1);
2766 
2767         private final int baseValue;
2768         private final ChronoLocalDate baseDate;
2769 
2770         /**
2771          * Constructor.
2772          *
2773          * @param field  the field to format, validated not null
2774          * @param minWidth  the minimum field width, from 1 to 10
2775          * @param maxWidth  the maximum field width, from 1 to 10
2776          * @param baseValue  the base value
2777          * @param baseDate  the base date
2778          */
2779         ReducedPrinterParser(TemporalField field, int minWidth, int maxWidth,
2780                 int baseValue, ChronoLocalDate baseDate) {
2781             this(field, minWidth, maxWidth, baseValue, baseDate, 0);
2782             if (minWidth < 1 || minWidth > 10) {
2783                 throw new IllegalArgumentException("The minWidth must be from 1 to 10 inclusive but was " + minWidth);
2784             }
2785             if (maxWidth < 1 || maxWidth > 10) {
2786                 throw new IllegalArgumentException("The maxWidth must be from 1 to 10 inclusive but was " + minWidth);
2787             }
2788             if (maxWidth < minWidth) {
2789                 throw new IllegalArgumentException("Maximum width must exceed or equal the minimum width but " +
2790                         maxWidth + " < " + minWidth);
2791             }
2792             if (baseDate == null) {
2793                 if (field.range().isValidValue(baseValue) == false) {
2794                     throw new IllegalArgumentException("The base value must be within the range of the field");
2795                 }
2796                 if ((((long) baseValue) + EXCEED_POINTS[maxWidth]) > Integer.MAX_VALUE) {
2797                     throw new DateTimeException("Unable to add printer-parser as the range exceeds the capacity of an int");
2798                 }
2799             }
2800         }
2801 
2802         /**
2803          * Constructor.
2804          * The arguments have already been checked.
2805          *
2806          * @param field  the field to format, validated not null
2807          * @param minWidth  the minimum field width, from 1 to 10
2808          * @param maxWidth  the maximum field width, from 1 to 10
2809          * @param baseValue  the base value
2810          * @param baseDate  the base date
2811          * @param subsequentWidth the subsequentWidth for this instance
2812          */
2813         private ReducedPrinterParser(TemporalField field, int minWidth, int maxWidth,
2814                 int baseValue, ChronoLocalDate baseDate, int subsequentWidth) {
2815             super(field, minWidth, maxWidth, SignStyle.NOT_NEGATIVE, subsequentWidth);
2816             this.baseValue = baseValue;
2817             this.baseDate = baseDate;
2818         }
2819 
2820         @Override
2821         long getValue(DateTimePrintContext context, long value) {
2822             long absValue = Math.abs(value);
2823             int baseValue = this.baseValue;
2824             if (baseDate != null) {
2825                 Chronology chrono = Chronology.from(context.getTemporal());
2826                 baseValue = chrono.date(baseDate).get(field);
2827             }
2828             if (value >= baseValue && value < baseValue + EXCEED_POINTS[minWidth]) {
2829                 // Use the reduced value if it fits in minWidth
2830                 return absValue % EXCEED_POINTS[minWidth];
2831             }
2832             // Otherwise truncate to fit in maxWidth
2833             return absValue % EXCEED_POINTS[maxWidth];
2834         }
2835 
2836         @Override
2837         int setValue(DateTimeParseContext context, long value, int errorPos, int successPos) {
2838             int baseValue = this.baseValue;
2839             if (baseDate != null) {
2840                 Chronology chrono = context.getEffectiveChronology();
2841                 baseValue = chrono.date(baseDate).get(field);
2842 
2843                 // In case the Chronology is changed later, add a callback when/if it changes
2844                 final long initialValue = value;
2845                 context.addChronoChangedListener(
2846                         (_unused) ->  {
2847                             /* Repeat the set of the field using the current Chronology
2848                              * The success/error position is ignored because the value is
2849                              * intentionally being overwritten.
2850                              */
2851                             setValue(context, initialValue, errorPos, successPos);
2852                         });
2853             }
2854             int parseLen = successPos - errorPos;
2855             if (parseLen == minWidth && value >= 0) {
2856                 long range = EXCEED_POINTS[minWidth];
2857                 long lastPart = baseValue % range;
2858                 long basePart = baseValue - lastPart;
2859                 if (baseValue > 0) {
2860                     value = basePart + value;
2861                 } else {
2862                     value = basePart - value;
2863                 }
2864                 if (value < baseValue) {
2865                     value += range;
2866                 }
2867             }
2868             return context.setParsedField(field, value, errorPos, successPos);
2869         }
2870 
2871         /**
2872          * Returns a new instance with fixed width flag set.
2873          *
2874          * @return a new updated printer-parser, not null
2875          */
2876         @Override
2877         ReducedPrinterParser withFixedWidth() {
2878             if (subsequentWidth == -1) {
2879                 return this;
2880             }
2881             return new ReducedPrinterParser(field, minWidth, maxWidth, baseValue, baseDate, -1);
2882         }
2883 
2884         /**
2885          * Returns a new instance with an updated subsequent width.
2886          *
2887          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater
2888          * @return a new updated printer-parser, not null
2889          */
2890         @Override
2891         ReducedPrinterParser withSubsequentWidth(int subsequentWidth) {
2892             return new ReducedPrinterParser(field, minWidth, maxWidth, baseValue, baseDate,
2893                     this.subsequentWidth + subsequentWidth);
2894         }
2895 
2896         /**
2897          * For a ReducedPrinterParser, fixed width is false if the mode is strict,
2898          * otherwise it is set as for NumberPrinterParser.
2899          * @param context the context
2900          * @return if the field is fixed width
2901          * @see DateTimeFormatterBuilder#appendValueReduced(java.time.temporal.TemporalField, int, int, int)
2902          */
2903         @Override
2904         boolean isFixedWidth(DateTimeParseContext context) {
2905            if (context.isStrict() == false) {
2906                return false;
2907            }
2908            return super.isFixedWidth(context);
2909         }
2910 
2911         @Override
2912         public String toString() {
2913             return "ReducedValue(" + field + "," + minWidth + "," + maxWidth +
2914                     "," + Objects.requireNonNullElse(baseDate, baseValue) + ")";
2915         }
2916     }
2917 
2918     //-----------------------------------------------------------------------
2919     /**
2920      * Prints and parses a numeric date-time field with optional padding.
2921      */
2922     static final class FractionPrinterParser implements DateTimePrinterParser {
2923         private final TemporalField field;
2924         private final int minWidth;
2925         private final int maxWidth;
2926         private final boolean decimalPoint;
2927 
2928         /**
2929          * Constructor.
2930          *
2931          * @param field  the field to output, not null
2932          * @param minWidth  the minimum width to output, from 0 to 9
2933          * @param maxWidth  the maximum width to output, from 0 to 9
2934          * @param decimalPoint  whether to output the localized decimal point symbol
2935          */
2936         FractionPrinterParser(TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) {
2937             Objects.requireNonNull(field, "field");
2938             if (field.range().isFixed() == false) {
2939                 throw new IllegalArgumentException("Field must have a fixed set of values: " + field);
2940             }
2941             if (minWidth < 0 || minWidth > 9) {
2942                 throw new IllegalArgumentException("Minimum width must be from 0 to 9 inclusive but was " + minWidth);
2943             }
2944             if (maxWidth < 1 || maxWidth > 9) {
2945                 throw new IllegalArgumentException("Maximum width must be from 1 to 9 inclusive but was " + maxWidth);
2946             }
2947             if (maxWidth < minWidth) {
2948                 throw new IllegalArgumentException("Maximum width must exceed or equal the minimum width but " +
2949                         maxWidth + " < " + minWidth);
2950             }
2951             this.field = field;
2952             this.minWidth = minWidth;
2953             this.maxWidth = maxWidth;
2954             this.decimalPoint = decimalPoint;
2955         }
2956 
2957         @Override
2958         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2959             Long value = context.getValue(field);
2960             if (value == null) {
2961                 return false;
2962             }
2963             DecimalStyle decimalStyle = context.getDecimalStyle();
2964             BigDecimal fraction = convertToFraction(value);
2965             if (fraction.scale() == 0) {  // scale is zero if value is zero
2966                 if (minWidth > 0) {
2967                     if (decimalPoint) {
2968                         buf.append(decimalStyle.getDecimalSeparator());
2969                     }
2970                     for (int i = 0; i < minWidth; i++) {
2971                         buf.append(decimalStyle.getZeroDigit());
2972                     }
2973                 }
2974             } else {
2975                 int outputScale = Math.min(Math.max(fraction.scale(), minWidth), maxWidth);
2976                 fraction = fraction.setScale(outputScale, RoundingMode.FLOOR);
2977                 String str = fraction.toPlainString().substring(2);
2978                 str = decimalStyle.convertNumberToI18N(str);
2979                 if (decimalPoint) {
2980                     buf.append(decimalStyle.getDecimalSeparator());
2981                 }
2982                 buf.append(str);
2983             }
2984             return true;
2985         }
2986 
2987         @Override
2988         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2989             int effectiveMin = (context.isStrict() ? minWidth : 0);
2990             int effectiveMax = (context.isStrict() ? maxWidth : 9);
2991             int length = text.length();
2992             if (position == length) {
2993                 // valid if whole field is optional, invalid if minimum width
2994                 return (effectiveMin > 0 ? ~position : position);
2995             }
2996             if (decimalPoint) {
2997                 if (text.charAt(position) != context.getDecimalStyle().getDecimalSeparator()) {
2998                     // valid if whole field is optional, invalid if minimum width
2999                     return (effectiveMin > 0 ? ~position : position);
3000                 }
3001                 position++;
3002             }
3003             int minEndPos = position + effectiveMin;
3004             if (minEndPos > length) {
3005                 return ~position;  // need at least min width digits
3006             }
3007             int maxEndPos = Math.min(position + effectiveMax, length);
3008             int total = 0;  // can use int because we are only parsing up to 9 digits
3009             int pos = position;
3010             while (pos < maxEndPos) {
3011                 char ch = text.charAt(pos++);
3012                 int digit = context.getDecimalStyle().convertToDigit(ch);
3013                 if (digit < 0) {
3014                     if (pos < minEndPos) {
3015                         return ~position;  // need at least min width digits
3016                     }
3017                     pos--;
3018                     break;
3019                 }
3020                 total = total * 10 + digit;
3021             }
3022             BigDecimal fraction = new BigDecimal(total).movePointLeft(pos - position);
3023             long value = convertFromFraction(fraction);
3024             return context.setParsedField(field, value, position, pos);
3025         }
3026 
3027         /**
3028          * Converts a value for this field to a fraction between 0 and 1.
3029          * <p>
3030          * The fractional value is between 0 (inclusive) and 1 (exclusive).
3031          * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
3032          * The fraction is obtained by calculation from the field range using 9 decimal
3033          * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
3034          * The calculation is inaccurate if the values do not run continuously from smallest to largest.
3035          * <p>
3036          * For example, the second-of-minute value of 15 would be returned as 0.25,
3037          * assuming the standard definition of 60 seconds in a minute.
3038          *
3039          * @param value  the value to convert, must be valid for this rule
3040          * @return the value as a fraction within the range, from 0 to 1, not null
3041          * @throws DateTimeException if the value cannot be converted to a fraction
3042          */
3043         private BigDecimal convertToFraction(long value) {
3044             ValueRange range = field.range();
3045             range.checkValidValue(value, field);
3046             BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
3047             BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
3048             BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD);
3049             BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR);
3050             // stripTrailingZeros bug
3051             return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros();
3052         }
3053 
3054         /**
3055          * Converts a fraction from 0 to 1 for this field to a value.
3056          * <p>
3057          * The fractional value must be between 0 (inclusive) and 1 (exclusive).
3058          * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
3059          * The value is obtained by calculation from the field range and a rounding
3060          * mode of {@link RoundingMode#FLOOR FLOOR}.
3061          * The calculation is inaccurate if the values do not run continuously from smallest to largest.
3062          * <p>
3063          * For example, the fractional second-of-minute of 0.25 would be converted to 15,
3064          * assuming the standard definition of 60 seconds in a minute.
3065          *
3066          * @param fraction  the fraction to convert, not null
3067          * @return the value of the field, valid for this rule
3068          * @throws DateTimeException if the value cannot be converted
3069          */
3070         private long convertFromFraction(BigDecimal fraction) {
3071             ValueRange range = field.range();
3072             BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
3073             BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
3074             BigDecimal valueBD = fraction.multiply(rangeBD).setScale(0, RoundingMode.FLOOR).add(minBD);
3075             return valueBD.longValueExact();
3076         }
3077 
3078         @Override
3079         public String toString() {
3080             String decimal = (decimalPoint ? ",DecimalPoint" : "");
3081             return "Fraction(" + field + "," + minWidth + "," + maxWidth + decimal + ")";
3082         }
3083     }
3084 
3085     //-----------------------------------------------------------------------
3086     /**
3087      * Prints or parses field text.
3088      */
3089     static final class TextPrinterParser implements DateTimePrinterParser {
3090         private final TemporalField field;
3091         private final TextStyle textStyle;
3092         private final DateTimeTextProvider provider;
3093         /**
3094          * The cached number printer parser.
3095          * Immutable and volatile, so no synchronization needed.
3096          */
3097         private volatile NumberPrinterParser numberPrinterParser;
3098 
3099         /**
3100          * Constructor.
3101          *
3102          * @param field  the field to output, not null
3103          * @param textStyle  the text style, not null
3104          * @param provider  the text provider, not null
3105          */
3106         TextPrinterParser(TemporalField field, TextStyle textStyle, DateTimeTextProvider provider) {
3107             // validated by caller
3108             this.field = field;
3109             this.textStyle = textStyle;
3110             this.provider = provider;
3111         }
3112 
3113         @Override
3114         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3115             Long value = context.getValue(field);
3116             if (value == null) {
3117                 return false;
3118             }
3119             String text;
3120             Chronology chrono = context.getTemporal().query(TemporalQueries.chronology());
3121             if (chrono == null || chrono == IsoChronology.INSTANCE) {
3122                 text = provider.getText(field, value, textStyle, context.getLocale());
3123             } else {
3124                 text = provider.getText(chrono, field, value, textStyle, context.getLocale());
3125             }
3126             if (text == null) {
3127                 return numberPrinterParser().format(context, buf);
3128             }
3129             buf.append(text);
3130             return true;
3131         }
3132 
3133         @Override
3134         public int parse(DateTimeParseContext context, CharSequence parseText, int position) {
3135             int length = parseText.length();
3136             if (position < 0 || position > length) {
3137                 throw new IndexOutOfBoundsException();
3138             }
3139             TextStyle style = (context.isStrict() ? textStyle : null);
3140             Chronology chrono = context.getEffectiveChronology();
3141             Iterator<Entry<String, Long>> it;
3142             if (chrono == null || chrono == IsoChronology.INSTANCE) {
3143                 it = provider.getTextIterator(field, style, context.getLocale());
3144             } else {
3145                 it = provider.getTextIterator(chrono, field, style, context.getLocale());
3146             }
3147             if (it != null) {
3148                 while (it.hasNext()) {
3149                     Entry<String, Long> entry = it.next();
3150                     String itText = entry.getKey();
3151                     if (context.subSequenceEquals(itText, 0, parseText, position, itText.length())) {
3152                         return context.setParsedField(field, entry.getValue(), position, position + itText.length());
3153                     }
3154                 }
3155                 if (field == ERA && !context.isStrict()) {
3156                     // parse the possible era name from era.toString()
3157                     List<Era> eras = chrono.eras();
3158                     for (Era era : eras) {
3159                         String name = era.toString();
3160                         if (context.subSequenceEquals(name, 0, parseText, position, name.length())) {
3161                             return context.setParsedField(field, era.getValue(), position, position + name.length());
3162                         }
3163                     }
3164                 }
3165                 if (context.isStrict()) {
3166                     return ~position;
3167                 }
3168             }
3169             return numberPrinterParser().parse(context, parseText, position);
3170         }
3171 
3172         /**
3173          * Create and cache a number printer parser.
3174          * @return the number printer parser for this field, not null
3175          */
3176         private NumberPrinterParser numberPrinterParser() {
3177             if (numberPrinterParser == null) {
3178                 numberPrinterParser = new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL);
3179             }
3180             return numberPrinterParser;
3181         }
3182 
3183         @Override
3184         public String toString() {
3185             if (textStyle == TextStyle.FULL) {
3186                 return "Text(" + field + ")";
3187             }
3188             return "Text(" + field + "," + textStyle + ")";
3189         }
3190     }
3191 
3192     //-----------------------------------------------------------------------
3193     /**
3194      * Prints or parses an ISO-8601 instant.
3195      */
3196     static final class InstantPrinterParser implements DateTimePrinterParser {
3197         // days in a 400 year cycle = 146097
3198         // days in a 10,000 year cycle = 146097 * 25
3199         // seconds per day = 86400
3200         private static final long SECONDS_PER_10000_YEARS = 146097L * 25L * 86400L;
3201         private static final long SECONDS_0000_TO_1970 = ((146097L * 5L) - (30L * 365L + 7L)) * 86400L;
3202         private final int fractionalDigits;
3203 
3204         InstantPrinterParser(int fractionalDigits) {
3205             this.fractionalDigits = fractionalDigits;
3206         }
3207 
3208         @Override
3209         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3210             // use INSTANT_SECONDS, thus this code is not bound by Instant.MAX
3211             Long inSecs = context.getValue(INSTANT_SECONDS);
3212             Long inNanos = null;
3213             if (context.getTemporal().isSupported(NANO_OF_SECOND)) {
3214                 inNanos = context.getTemporal().getLong(NANO_OF_SECOND);
3215             }
3216             if (inSecs == null) {
3217                 return false;
3218             }
3219             long inSec = inSecs;
3220             int inNano = NANO_OF_SECOND.checkValidIntValue(inNanos != null ? inNanos : 0);
3221             // format mostly using LocalDateTime.toString
3222             if (inSec >= -SECONDS_0000_TO_1970) {
3223                 // current era
3224                 long zeroSecs = inSec - SECONDS_PER_10000_YEARS + SECONDS_0000_TO_1970;
3225                 long hi = Math.floorDiv(zeroSecs, SECONDS_PER_10000_YEARS) + 1;
3226                 long lo = Math.floorMod(zeroSecs, SECONDS_PER_10000_YEARS);
3227                 LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC);
3228                 if (hi > 0) {
3229                     buf.append('+').append(hi);
3230                 }
3231                 buf.append(ldt);
3232                 if (ldt.getSecond() == 0) {
3233                     buf.append(":00");
3234                 }
3235             } else {
3236                 // before current era
3237                 long zeroSecs = inSec + SECONDS_0000_TO_1970;
3238                 long hi = zeroSecs / SECONDS_PER_10000_YEARS;
3239                 long lo = zeroSecs % SECONDS_PER_10000_YEARS;
3240                 LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC);
3241                 int pos = buf.length();
3242                 buf.append(ldt);
3243                 if (ldt.getSecond() == 0) {
3244                     buf.append(":00");
3245                 }
3246                 if (hi < 0) {
3247                     if (ldt.getYear() == -10_000) {
3248                         buf.replace(pos, pos + 2, Long.toString(hi - 1));
3249                     } else if (lo == 0) {
3250                         buf.insert(pos, hi);
3251                     } else {
3252                         buf.insert(pos + 1, Math.abs(hi));
3253                     }
3254                 }
3255             }
3256             // add fraction
3257             if ((fractionalDigits < 0 && inNano > 0) || fractionalDigits > 0) {
3258                 buf.append('.');
3259                 int div = 100_000_000;
3260                 for (int i = 0; ((fractionalDigits == -1 && inNano > 0) ||
3261                                     (fractionalDigits == -2 && (inNano > 0 || (i % 3) != 0)) ||
3262                                     i < fractionalDigits); i++) {
3263                     int digit = inNano / div;
3264                     buf.append((char) (digit + '0'));
3265                     inNano = inNano - (digit * div);
3266                     div = div / 10;
3267                 }
3268             }
3269             buf.append('Z');
3270             return true;
3271         }
3272 
3273         @Override
3274         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3275             // new context to avoid overwriting fields like year/month/day
3276             int minDigits = (fractionalDigits < 0 ? 0 : fractionalDigits);
3277             int maxDigits = (fractionalDigits < 0 ? 9 : fractionalDigits);
3278             CompositePrinterParser parser = new DateTimeFormatterBuilder()
3279                     .append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T')
3280                     .appendValue(HOUR_OF_DAY, 2).appendLiteral(':')
3281                     .appendValue(MINUTE_OF_HOUR, 2).appendLiteral(':')
3282                     .appendValue(SECOND_OF_MINUTE, 2)
3283                     .appendFraction(NANO_OF_SECOND, minDigits, maxDigits, true)
3284                     .appendLiteral('Z')
3285                     .toFormatter().toPrinterParser(false);
3286             DateTimeParseContext newContext = context.copy();
3287             int pos = parser.parse(newContext, text, position);
3288             if (pos < 0) {
3289                 return pos;
3290             }
3291             // parser restricts most fields to 2 digits, so definitely int
3292             // correctly parsed nano is also guaranteed to be valid
3293             long yearParsed = newContext.getParsed(YEAR);
3294             int month = newContext.getParsed(MONTH_OF_YEAR).intValue();
3295             int day = newContext.getParsed(DAY_OF_MONTH).intValue();
3296             int hour = newContext.getParsed(HOUR_OF_DAY).intValue();
3297             int min = newContext.getParsed(MINUTE_OF_HOUR).intValue();
3298             Long secVal = newContext.getParsed(SECOND_OF_MINUTE);
3299             Long nanoVal = newContext.getParsed(NANO_OF_SECOND);
3300             int sec = (secVal != null ? secVal.intValue() : 0);
3301             int nano = (nanoVal != null ? nanoVal.intValue() : 0);
3302             int days = 0;
3303             if (hour == 24 && min == 0 && sec == 0 && nano == 0) {
3304                 hour = 0;
3305                 days = 1;
3306             } else if (hour == 23 && min == 59 && sec == 60) {
3307                 context.setParsedLeapSecond();
3308                 sec = 59;
3309             }
3310             int year = (int) yearParsed % 10_000;
3311             long instantSecs;
3312             try {
3313                 LocalDateTime ldt = LocalDateTime.of(year, month, day, hour, min, sec, 0).plusDays(days);
3314                 instantSecs = ldt.toEpochSecond(ZoneOffset.UTC);
3315                 instantSecs += Math.multiplyExact(yearParsed / 10_000L, SECONDS_PER_10000_YEARS);
3316             } catch (RuntimeException ex) {
3317                 return ~position;
3318             }
3319             int successPos = pos;
3320             successPos = context.setParsedField(INSTANT_SECONDS, instantSecs, position, successPos);
3321             return context.setParsedField(NANO_OF_SECOND, nano, position, successPos);
3322         }
3323 
3324         @Override
3325         public String toString() {
3326             return "Instant()";
3327         }
3328     }
3329 
3330     //-----------------------------------------------------------------------
3331     /**
3332      * Prints or parses an offset ID.
3333      */
3334     static final class OffsetIdPrinterParser implements DateTimePrinterParser {
3335         static final String[] PATTERNS = new String[] {
3336             "+HH", "+HHmm", "+HH:mm", "+HHMM", "+HH:MM", "+HHMMss", "+HH:MM:ss", "+HHMMSS", "+HH:MM:SS", "+HHmmss", "+HH:mm:ss",
3337         };  // order used in pattern builder
3338         static final OffsetIdPrinterParser INSTANCE_ID_Z = new OffsetIdPrinterParser("+HH:MM:ss", "Z");
3339         static final OffsetIdPrinterParser INSTANCE_ID_ZERO = new OffsetIdPrinterParser("+HH:MM:ss", "0");
3340 
3341         private final String noOffsetText;
3342         private final int type;
3343 
3344         /**
3345          * Constructor.
3346          *
3347          * @param pattern  the pattern
3348          * @param noOffsetText  the text to use for UTC, not null
3349          */
3350         OffsetIdPrinterParser(String pattern, String noOffsetText) {
3351             Objects.requireNonNull(pattern, "pattern");
3352             Objects.requireNonNull(noOffsetText, "noOffsetText");
3353             this.type = checkPattern(pattern);
3354             this.noOffsetText = noOffsetText;
3355         }
3356 
3357         private int checkPattern(String pattern) {
3358             for (int i = 0; i < PATTERNS.length; i++) {
3359                 if (PATTERNS[i].equals(pattern)) {
3360                     return i;
3361                 }
3362             }
3363             throw new IllegalArgumentException("Invalid zone offset pattern: " + pattern);
3364         }
3365 
3366         @Override
3367         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3368             Long offsetSecs = context.getValue(OFFSET_SECONDS);
3369             if (offsetSecs == null) {
3370                 return false;
3371             }
3372             int totalSecs = Math.toIntExact(offsetSecs);
3373             if (totalSecs == 0) {
3374                 buf.append(noOffsetText);
3375             } else {
3376                 int absHours = Math.abs((totalSecs / 3600) % 100);  // anything larger than 99 silently dropped
3377                 int absMinutes = Math.abs((totalSecs / 60) % 60);
3378                 int absSeconds = Math.abs(totalSecs % 60);
3379                 int bufPos = buf.length();
3380                 int output = absHours;
3381                 buf.append(totalSecs < 0 ? "-" : "+")
3382                     .append((char) (absHours / 10 + '0')).append((char) (absHours % 10 + '0'));
3383                 if ((type >= 3 && type < 9) || (type >= 9 && absSeconds > 0) || (type >= 1 && absMinutes > 0)) {
3384                     buf.append((type % 2) == 0 ? ":" : "")
3385                         .append((char) (absMinutes / 10 + '0')).append((char) (absMinutes % 10 + '0'));
3386                     output += absMinutes;
3387                     if (type == 7  || type == 8 || (type >= 5 && absSeconds > 0)) {
3388                         buf.append((type % 2) == 0 ? ":" : "")
3389                             .append((char) (absSeconds / 10 + '0')).append((char) (absSeconds % 10 + '0'));
3390                         output += absSeconds;
3391                     }
3392                 }
3393                 if (output == 0) {
3394                     buf.setLength(bufPos);
3395                     buf.append(noOffsetText);
3396                 }
3397             }
3398             return true;
3399         }
3400 
3401         @Override
3402         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3403             int length = text.length();
3404             int noOffsetLen = noOffsetText.length();
3405             int parseType = type;
3406             if (context.isStrict() == false) {
3407                 if ((parseType > 0 && (parseType % 2) == 0) ||
3408                     (parseType == 0 && length > position + 3 && text.charAt(position + 3) == ':')) {
3409                     parseType = 10;
3410                 } else {
3411                     parseType = 9;
3412                 }
3413             }
3414             if (noOffsetLen == 0) {
3415                 if (position == length) {
3416                     return context.setParsedField(OFFSET_SECONDS, 0, position, position);
3417                 }
3418             } else {
3419                 if (position == length) {
3420                     return ~position;
3421                 }
3422                 if (context.subSequenceEquals(text, position, noOffsetText, 0, noOffsetLen)) {
3423                     return context.setParsedField(OFFSET_SECONDS, 0, position, position + noOffsetLen);
3424                 }
3425             }
3426 
3427             // parse normal plus/minus offset
3428             char sign = text.charAt(position);  // IOOBE if invalid position
3429             if (sign == '+' || sign == '-') {
3430                 // starts
3431                 int negative = (sign == '-' ? -1 : 1);
3432                 int[] array = new int[4];
3433                 array[0] = position + 1;
3434                 if ((parseNumber(array, 1, text, true, parseType) ||
3435                         parseNumber(array, 2, text, parseType >= 3 && parseType < 9, parseType) ||
3436                         parseNumber(array, 3, text, parseType == 7 || parseType == 8, parseType)) == false) {
3437                     // success
3438                     long offsetSecs = negative * (array[1] * 3600L + array[2] * 60L + array[3]);
3439                     return context.setParsedField(OFFSET_SECONDS, offsetSecs, position, array[0]);
3440                 }
3441             }
3442             // handle special case of empty no offset text
3443             if (noOffsetLen == 0) {
3444                 return context.setParsedField(OFFSET_SECONDS, 0, position, position);
3445             }
3446             return ~position;
3447         }
3448 
3449         /**
3450          * Parse a two digit zero-prefixed number.
3451          *
3452          * @param array  the array of parsed data, 0=pos,1=hours,2=mins,3=secs, not null
3453          * @param arrayIndex  the index to parse the value into
3454          * @param parseText  the offset ID, not null
3455          * @param required  whether this number is required
3456          * @param parseType the offset pattern type
3457          * @return true if an error occurred
3458          */
3459         private boolean parseNumber(int[] array, int arrayIndex, CharSequence parseText, boolean required, int parseType) {
3460             if ((parseType + 3) / 2 < arrayIndex) {
3461                 return false;  // ignore seconds/minutes
3462             }
3463             int pos = array[0];
3464             if ((parseType % 2) == 0 && arrayIndex > 1) {
3465                 if (pos + 1 > parseText.length() || parseText.charAt(pos) != ':') {
3466                     return required;
3467                 }
3468                 pos++;
3469             }
3470             if (pos + 2 > parseText.length()) {
3471                 return required;
3472             }
3473             char ch1 = parseText.charAt(pos++);
3474             char ch2 = parseText.charAt(pos++);
3475             if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') {
3476                 return required;
3477             }
3478             int value = (ch1 - 48) * 10 + (ch2 - 48);
3479             if (value < 0 || value > 59) {
3480                 return required;
3481             }
3482             array[arrayIndex] = value;
3483             array[0] = pos;
3484             return false;
3485         }
3486 
3487         @Override
3488         public String toString() {
3489             String converted = noOffsetText.replace("'", "''");
3490             return "Offset(" + PATTERNS[type] + ",'" + converted + "')";
3491         }
3492     }
3493 
3494     //-----------------------------------------------------------------------
3495     /**
3496      * Prints or parses an offset ID.
3497      */
3498     static final class LocalizedOffsetIdPrinterParser implements DateTimePrinterParser {
3499         private final TextStyle style;
3500 
3501         /**
3502          * Constructor.
3503          *
3504          * @param style  the style, not null
3505          */
3506         LocalizedOffsetIdPrinterParser(TextStyle style) {
3507             this.style = style;
3508         }
3509 
3510         private static StringBuilder appendHMS(StringBuilder buf, int t) {
3511             return buf.append((char)(t / 10 + '0'))
3512                       .append((char)(t % 10 + '0'));
3513         }
3514 
3515         @Override
3516         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3517             Long offsetSecs = context.getValue(OFFSET_SECONDS);
3518             if (offsetSecs == null) {
3519                 return false;
3520             }
3521             String gmtText = "GMT";  // TODO: get localized version of 'GMT'
3522             buf.append(gmtText);
3523             int totalSecs = Math.toIntExact(offsetSecs);
3524             if (totalSecs != 0) {
3525                 int absHours = Math.abs((totalSecs / 3600) % 100);  // anything larger than 99 silently dropped
3526                 int absMinutes = Math.abs((totalSecs / 60) % 60);
3527                 int absSeconds = Math.abs(totalSecs % 60);
3528                 buf.append(totalSecs < 0 ? "-" : "+");
3529                 if (style == TextStyle.FULL) {
3530                     appendHMS(buf, absHours);
3531                     buf.append(':');
3532                     appendHMS(buf, absMinutes);
3533                     if (absSeconds != 0) {
3534                        buf.append(':');
3535                        appendHMS(buf, absSeconds);
3536                     }
3537                 } else {
3538                     if (absHours >= 10) {
3539                         buf.append((char)(absHours / 10 + '0'));
3540                     }
3541                     buf.append((char)(absHours % 10 + '0'));
3542                     if (absMinutes != 0 || absSeconds != 0) {
3543                         buf.append(':');
3544                         appendHMS(buf, absMinutes);
3545                         if (absSeconds != 0) {
3546                             buf.append(':');
3547                             appendHMS(buf, absSeconds);
3548                         }
3549                     }
3550                 }
3551             }
3552             return true;
3553         }
3554 
3555         int getDigit(CharSequence text, int position) {
3556             char c = text.charAt(position);
3557             if (c < '0' || c > '9') {
3558                 return -1;
3559             }
3560             return c - '0';
3561         }
3562 
3563         @Override
3564         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3565             int pos = position;
3566             int end = text.length();
3567             String gmtText = "GMT";  // TODO: get localized version of 'GMT'
3568             if (!context.subSequenceEquals(text, pos, gmtText, 0, gmtText.length())) {
3569                     return ~position;
3570                 }
3571             pos += gmtText.length();
3572             // parse normal plus/minus offset
3573             int negative = 0;
3574             if (pos == end) {
3575                 return context.setParsedField(OFFSET_SECONDS, 0, position, pos);
3576             }
3577             char sign = text.charAt(pos);  // IOOBE if invalid position
3578             if (sign == '+') {
3579                 negative = 1;
3580             } else if (sign == '-') {
3581                 negative = -1;
3582             } else {
3583                 return context.setParsedField(OFFSET_SECONDS, 0, position, pos);
3584             }
3585             pos++;
3586             int h = 0;
3587             int m = 0;
3588             int s = 0;
3589             if (style == TextStyle.FULL) {
3590                 int h1 = getDigit(text, pos++);
3591                 int h2 = getDigit(text, pos++);
3592                 if (h1 < 0 || h2 < 0 || text.charAt(pos++) != ':') {
3593                     return ~position;
3594                 }
3595                 h = h1 * 10 + h2;
3596                 int m1 = getDigit(text, pos++);
3597                 int m2 = getDigit(text, pos++);
3598                 if (m1 < 0 || m2 < 0) {
3599                     return ~position;
3600                 }
3601                 m = m1 * 10 + m2;
3602                 if (pos + 2 < end && text.charAt(pos) == ':') {
3603                     int s1 = getDigit(text, pos + 1);
3604                     int s2 = getDigit(text, pos + 2);
3605                     if (s1 >= 0 && s2 >= 0) {
3606                         s = s1 * 10 + s2;
3607                         pos += 3;
3608                     }
3609                 }
3610             } else {
3611                 h = getDigit(text, pos++);
3612                 if (h < 0) {
3613                     return ~position;
3614                 }
3615                 if (pos < end) {
3616                     int h2 = getDigit(text, pos);
3617                     if (h2 >=0) {
3618                         h = h * 10 + h2;
3619                         pos++;
3620                     }
3621                     if (pos + 2 < end && text.charAt(pos) == ':') {
3622                         if (pos + 2 < end && text.charAt(pos) == ':') {
3623                             int m1 = getDigit(text, pos + 1);
3624                             int m2 = getDigit(text, pos + 2);
3625                             if (m1 >= 0 && m2 >= 0) {
3626                                 m = m1 * 10 + m2;
3627                                 pos += 3;
3628                                 if (pos + 2 < end && text.charAt(pos) == ':') {
3629                                     int s1 = getDigit(text, pos + 1);
3630                                     int s2 = getDigit(text, pos + 2);
3631                                     if (s1 >= 0 && s2 >= 0) {
3632                                         s = s1 * 10 + s2;
3633                                         pos += 3;
3634                                    }
3635                                 }
3636                             }
3637                         }
3638                     }
3639                 }
3640             }
3641             long offsetSecs = negative * (h * 3600L + m * 60L + s);
3642             return context.setParsedField(OFFSET_SECONDS, offsetSecs, position, pos);
3643         }
3644 
3645         @Override
3646         public String toString() {
3647             return "LocalizedOffset(" + style + ")";
3648         }
3649     }
3650 
3651     //-----------------------------------------------------------------------
3652     /**
3653      * Prints or parses a zone ID.
3654      */
3655     static final class ZoneTextPrinterParser extends ZoneIdPrinterParser {
3656 
3657         /** The text style to output. */
3658         private final TextStyle textStyle;
3659 
3660         /** The preferred zoneid map */
3661         private Set<String> preferredZones;
3662 
3663         ZoneTextPrinterParser(TextStyle textStyle, Set<ZoneId> preferredZones) {
3664             super(TemporalQueries.zone(), "ZoneText(" + textStyle + ")");
3665             this.textStyle = Objects.requireNonNull(textStyle, "textStyle");
3666             if (preferredZones != null && preferredZones.size() != 0) {
3667                 this.preferredZones = new HashSet<>();
3668                 for (ZoneId id : preferredZones) {
3669                     this.preferredZones.add(id.getId());
3670                 }
3671             }
3672         }
3673 
3674         private static final int STD = 0;
3675         private static final int DST = 1;
3676         private static final int GENERIC = 2;
3677         private static final Map<String, SoftReference<Map<Locale, String[]>>> cache =
3678             new ConcurrentHashMap<>();
3679 
3680         private String getDisplayName(String id, int type, Locale locale) {
3681             if (textStyle == TextStyle.NARROW) {
3682                 return null;
3683             }
3684             String[] names;
3685             SoftReference<Map<Locale, String[]>> ref = cache.get(id);
3686             Map<Locale, String[]> perLocale = null;
3687             if (ref == null || (perLocale = ref.get()) == null ||
3688                 (names = perLocale.get(locale)) == null) {
3689                 names = TimeZoneNameUtility.retrieveDisplayNames(id, locale);
3690                 if (names == null) {
3691                     return null;
3692                 }
3693                 names = Arrays.copyOfRange(names, 0, 7);
3694                 names[5] =
3695                     TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.LONG, locale);
3696                 if (names[5] == null) {
3697                     names[5] = names[0]; // use the id
3698                 }
3699                 names[6] =
3700                     TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.SHORT, locale);
3701                 if (names[6] == null) {
3702                     names[6] = names[0];
3703                 }
3704                 if (perLocale == null) {
3705                     perLocale = new ConcurrentHashMap<>();
3706                 }
3707                 perLocale.put(locale, names);
3708                 cache.put(id, new SoftReference<>(perLocale));
3709             }
3710             switch (type) {
3711             case STD:
3712                 return names[textStyle.zoneNameStyleIndex() + 1];
3713             case DST:
3714                 return names[textStyle.zoneNameStyleIndex() + 3];
3715             }
3716             return names[textStyle.zoneNameStyleIndex() + 5];
3717         }
3718 
3719         @Override
3720         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3721             ZoneId zone = context.getValue(TemporalQueries.zoneId());
3722             if (zone == null) {
3723                 return false;
3724             }
3725             String zname = zone.getId();
3726             if (!(zone instanceof ZoneOffset)) {
3727                 TemporalAccessor dt = context.getTemporal();
3728                 String name = getDisplayName(zname,
3729                                              dt.isSupported(ChronoField.INSTANT_SECONDS)
3730                                              ? (zone.getRules().isDaylightSavings(Instant.from(dt)) ? DST : STD)
3731                                              : GENERIC,
3732                                              context.getLocale());
3733                 if (name != null) {
3734                     zname = name;
3735                 }
3736             }
3737             buf.append(zname);
3738             return true;
3739         }
3740 
3741         // cache per instance for now
3742         private final Map<Locale, Entry<Integer, SoftReference<PrefixTree>>>
3743             cachedTree = new HashMap<>();
3744         private final Map<Locale, Entry<Integer, SoftReference<PrefixTree>>>
3745             cachedTreeCI = new HashMap<>();
3746 
3747         @Override
3748         protected PrefixTree getTree(DateTimeParseContext context) {
3749             if (textStyle == TextStyle.NARROW) {
3750                 return super.getTree(context);
3751             }
3752             Locale locale = context.getLocale();
3753             boolean isCaseSensitive = context.isCaseSensitive();
3754             Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
3755             int regionIdsSize = regionIds.size();
3756 
3757             Map<Locale, Entry<Integer, SoftReference<PrefixTree>>> cached =
3758                 isCaseSensitive ? cachedTree : cachedTreeCI;
3759 
3760             Entry<Integer, SoftReference<PrefixTree>> entry = null;
3761             PrefixTree tree = null;
3762             String[][] zoneStrings = null;
3763             if ((entry = cached.get(locale)) == null ||
3764                 (entry.getKey() != regionIdsSize ||
3765                 (tree = entry.getValue().get()) == null)) {
3766                 tree = PrefixTree.newTree(context);
3767                 zoneStrings = TimeZoneNameUtility.getZoneStrings(locale);
3768                 for (String[] names : zoneStrings) {
3769                     String zid = names[0];
3770                     if (!regionIds.contains(zid)) {
3771                         continue;
3772                     }
3773                     tree.add(zid, zid);    // don't convert zid -> metazone
3774                     zid = ZoneName.toZid(zid, locale);
3775                     int i = textStyle == TextStyle.FULL ? 1 : 2;
3776                     for (; i < names.length; i += 2) {
3777                         tree.add(names[i], zid);
3778                     }
3779                 }
3780                 // if we have a set of preferred zones, need a copy and
3781                 // add the preferred zones again to overwrite
3782                 if (preferredZones != null) {
3783                     for (String[] names : zoneStrings) {
3784                         String zid = names[0];
3785                         if (!preferredZones.contains(zid) || !regionIds.contains(zid)) {
3786                             continue;
3787                         }
3788                         int i = textStyle == TextStyle.FULL ? 1 : 2;
3789                         for (; i < names.length; i += 2) {
3790                             tree.add(names[i], zid);
3791                        }
3792                     }
3793                 }
3794                 cached.put(locale, new SimpleImmutableEntry<>(regionIdsSize, new SoftReference<>(tree)));
3795             }
3796             return tree;
3797         }
3798     }
3799 
3800     //-----------------------------------------------------------------------
3801     /**
3802      * Prints or parses a zone ID.
3803      */
3804     static class ZoneIdPrinterParser implements DateTimePrinterParser {
3805         private final TemporalQuery<ZoneId> query;
3806         private final String description;
3807 
3808         ZoneIdPrinterParser(TemporalQuery<ZoneId> query, String description) {
3809             this.query = query;
3810             this.description = description;
3811         }
3812 
3813         @Override
3814         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3815             ZoneId zone = context.getValue(query);
3816             if (zone == null) {
3817                 return false;
3818             }
3819             buf.append(zone.getId());
3820             return true;
3821         }
3822 
3823         /**
3824          * The cached tree to speed up parsing.
3825          */
3826         private static volatile Entry<Integer, PrefixTree> cachedPrefixTree;
3827         private static volatile Entry<Integer, PrefixTree> cachedPrefixTreeCI;
3828 
3829         protected PrefixTree getTree(DateTimeParseContext context) {
3830             // prepare parse tree
3831             Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
3832             final int regionIdsSize = regionIds.size();
3833             Entry<Integer, PrefixTree> cached = context.isCaseSensitive()
3834                                                 ? cachedPrefixTree : cachedPrefixTreeCI;
3835             if (cached == null || cached.getKey() != regionIdsSize) {
3836                 synchronized (this) {
3837                     cached = context.isCaseSensitive() ? cachedPrefixTree : cachedPrefixTreeCI;
3838                     if (cached == null || cached.getKey() != regionIdsSize) {
3839                         cached = new SimpleImmutableEntry<>(regionIdsSize, PrefixTree.newTree(regionIds, context));
3840                         if (context.isCaseSensitive()) {
3841                             cachedPrefixTree = cached;
3842                         } else {
3843                             cachedPrefixTreeCI = cached;
3844                         }
3845                     }
3846                 }
3847             }
3848             return cached.getValue();
3849         }
3850 
3851         /**
3852          * This implementation looks for the longest matching string.
3853          * For example, parsing Etc/GMT-2 will return Etc/GMC-2 rather than just
3854          * Etc/GMC although both are valid.
3855          */
3856         @Override
3857         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3858             int length = text.length();
3859             if (position > length) {
3860                 throw new IndexOutOfBoundsException();
3861             }
3862             if (position == length) {
3863                 return ~position;
3864             }
3865 
3866             // handle fixed time-zone IDs
3867             char nextChar = text.charAt(position);
3868             if (nextChar == '+' || nextChar == '-') {
3869                 return parseOffsetBased(context, text, position, position, OffsetIdPrinterParser.INSTANCE_ID_Z);
3870             } else if (length >= position + 2) {
3871                 char nextNextChar = text.charAt(position + 1);
3872                 if (context.charEquals(nextChar, 'U') && context.charEquals(nextNextChar, 'T')) {
3873                     if (length >= position + 3 && context.charEquals(text.charAt(position + 2), 'C')) {
3874                         return parseOffsetBased(context, text, position, position + 3, OffsetIdPrinterParser.INSTANCE_ID_ZERO);
3875                     }
3876                     return parseOffsetBased(context, text, position, position + 2, OffsetIdPrinterParser.INSTANCE_ID_ZERO);
3877                 } else if (context.charEquals(nextChar, 'G') && length >= position + 3 &&
3878                         context.charEquals(nextNextChar, 'M') && context.charEquals(text.charAt(position + 2), 'T')) {
3879                     if (length >= position + 4 && context.charEquals(text.charAt(position + 3), '0')) {
3880                         context.setParsed(ZoneId.of("GMT0"));
3881                         return position + 4;
3882                     }
3883                     return parseOffsetBased(context, text, position, position + 3, OffsetIdPrinterParser.INSTANCE_ID_ZERO);
3884                 }
3885             }
3886 
3887             // parse
3888             PrefixTree tree = getTree(context);
3889             ParsePosition ppos = new ParsePosition(position);
3890             String parsedZoneId = tree.match(text, ppos);
3891             if (parsedZoneId == null) {
3892                 if (context.charEquals(nextChar, 'Z')) {
3893                     context.setParsed(ZoneOffset.UTC);
3894                     return position + 1;
3895                 }
3896                 return ~position;
3897             }
3898             context.setParsed(ZoneId.of(parsedZoneId));
3899             return ppos.getIndex();
3900         }
3901 
3902         /**
3903          * Parse an offset following a prefix and set the ZoneId if it is valid.
3904          * To matching the parsing of ZoneId.of the values are not normalized
3905          * to ZoneOffsets.
3906          *
3907          * @param context the parse context
3908          * @param text the input text
3909          * @param prefixPos start of the prefix
3910          * @param position start of text after the prefix
3911          * @param parser parser for the value after the prefix
3912          * @return the position after the parse
3913          */
3914         private int parseOffsetBased(DateTimeParseContext context, CharSequence text, int prefixPos, int position, OffsetIdPrinterParser parser) {
3915             String prefix = text.toString().substring(prefixPos, position).toUpperCase();
3916             if (position >= text.length()) {
3917                 context.setParsed(ZoneId.of(prefix));
3918                 return position;
3919             }
3920 
3921             // '0' or 'Z' after prefix is not part of a valid ZoneId; use bare prefix
3922             if (text.charAt(position) == '0' ||
3923                 context.charEquals(text.charAt(position), 'Z')) {
3924                 context.setParsed(ZoneId.of(prefix));
3925                 return position;
3926             }
3927 
3928             DateTimeParseContext newContext = context.copy();
3929             int endPos = parser.parse(newContext, text, position);
3930             try {
3931                 if (endPos < 0) {
3932                     if (parser == OffsetIdPrinterParser.INSTANCE_ID_Z) {
3933                         return ~prefixPos;
3934                     }
3935                     context.setParsed(ZoneId.of(prefix));
3936                     return position;
3937                 }
3938                 int offset = (int) newContext.getParsed(OFFSET_SECONDS).longValue();
3939                 ZoneOffset zoneOffset = ZoneOffset.ofTotalSeconds(offset);
3940                 context.setParsed(ZoneId.ofOffset(prefix, zoneOffset));
3941                 return endPos;
3942             } catch (DateTimeException dte) {
3943                 return ~prefixPos;
3944             }
3945         }
3946 
3947         @Override
3948         public String toString() {
3949             return description;
3950         }
3951     }
3952 
3953     //-----------------------------------------------------------------------
3954     /**
3955      * A String based prefix tree for parsing time-zone names.
3956      */
3957     static class PrefixTree {
3958         protected String key;
3959         protected String value;
3960         protected char c0;    // performance optimization to avoid the
3961                               // boundary check cost of key.charat(0)
3962         protected PrefixTree child;
3963         protected PrefixTree sibling;
3964 
3965         private PrefixTree(String k, String v, PrefixTree child) {
3966             this.key = k;
3967             this.value = v;
3968             this.child = child;
3969             if (k.length() == 0){
3970                 c0 = 0xffff;
3971             } else {
3972                 c0 = key.charAt(0);
3973             }
3974         }
3975 
3976         /**
3977          * Creates a new prefix parsing tree based on parse context.
3978          *
3979          * @param context  the parse context
3980          * @return the tree, not null
3981          */
3982         public static PrefixTree newTree(DateTimeParseContext context) {
3983             //if (!context.isStrict()) {
3984             //    return new LENIENT("", null, null);
3985             //}
3986             if (context.isCaseSensitive()) {
3987                 return new PrefixTree("", null, null);
3988             }
3989             return new CI("", null, null);
3990         }
3991 
3992         /**
3993          * Creates a new prefix parsing tree.
3994          *
3995          * @param keys  a set of strings to build the prefix parsing tree, not null
3996          * @param context  the parse context
3997          * @return the tree, not null
3998          */
3999         public static  PrefixTree newTree(Set<String> keys, DateTimeParseContext context) {
4000             PrefixTree tree = newTree(context);
4001             for (String k : keys) {
4002                 tree.add0(k, k);
4003             }
4004             return tree;
4005         }
4006 
4007         /**
4008          * Clone a copy of this tree
4009          */
4010         public PrefixTree copyTree() {
4011             PrefixTree copy = new PrefixTree(key, value, null);
4012             if (child != null) {
4013                 copy.child = child.copyTree();
4014             }
4015             if (sibling != null) {
4016                 copy.sibling = sibling.copyTree();
4017             }
4018             return copy;
4019         }
4020 
4021 
4022         /**
4023          * Adds a pair of {key, value} into the prefix tree.
4024          *
4025          * @param k  the key, not null
4026          * @param v  the value, not null
4027          * @return  true if the pair is added successfully
4028          */
4029         public boolean add(String k, String v) {
4030             return add0(k, v);
4031         }
4032 
4033         private boolean add0(String k, String v) {
4034             k = toKey(k);
4035             int prefixLen = prefixLength(k);
4036             if (prefixLen == key.length()) {
4037                 if (prefixLen < k.length()) {  // down the tree
4038                     String subKey = k.substring(prefixLen);
4039                     PrefixTree c = child;
4040                     while (c != null) {
4041                         if (isEqual(c.c0, subKey.charAt(0))) {
4042                             return c.add0(subKey, v);
4043                         }
4044                         c = c.sibling;
4045                     }
4046                     // add the node as the child of the current node
4047                     c = newNode(subKey, v, null);
4048                     c.sibling = child;
4049                     child = c;
4050                     return true;
4051                 }
4052                 // have an existing <key, value> already, overwrite it
4053                 // if (value != null) {
4054                 //    return false;
4055                 //}
4056                 value = v;
4057                 return true;
4058             }
4059             // split the existing node
4060             PrefixTree n1 = newNode(key.substring(prefixLen), value, child);
4061             key = k.substring(0, prefixLen);
4062             child = n1;
4063             if (prefixLen < k.length()) {
4064                 PrefixTree n2 = newNode(k.substring(prefixLen), v, null);
4065                 child.sibling = n2;
4066                 value = null;
4067             } else {
4068                 value = v;
4069             }
4070             return true;
4071         }
4072 
4073         /**
4074          * Match text with the prefix tree.
4075          *
4076          * @param text  the input text to parse, not null
4077          * @param off  the offset position to start parsing at
4078          * @param end  the end position to stop parsing
4079          * @return the resulting string, or null if no match found.
4080          */
4081         public String match(CharSequence text, int off, int end) {
4082             if (!prefixOf(text, off, end)){
4083                 return null;
4084             }
4085             if (child != null && (off += key.length()) != end) {
4086                 PrefixTree c = child;
4087                 do {
4088                     if (isEqual(c.c0, text.charAt(off))) {
4089                         String found = c.match(text, off, end);
4090                         if (found != null) {
4091                             return found;
4092                         }
4093                         return value;
4094                     }
4095                     c = c.sibling;
4096                 } while (c != null);
4097             }
4098             return value;
4099         }
4100 
4101         /**
4102          * Match text with the prefix tree.
4103          *
4104          * @param text  the input text to parse, not null
4105          * @param pos  the position to start parsing at, from 0 to the text
4106          *  length. Upon return, position will be updated to the new parse
4107          *  position, or unchanged, if no match found.
4108          * @return the resulting string, or null if no match found.
4109          */
4110         public String match(CharSequence text, ParsePosition pos) {
4111             int off = pos.getIndex();
4112             int end = text.length();
4113             if (!prefixOf(text, off, end)){
4114                 return null;
4115             }
4116             off += key.length();
4117             if (child != null && off != end) {
4118                 PrefixTree c = child;
4119                 do {
4120                     if (isEqual(c.c0, text.charAt(off))) {
4121                         pos.setIndex(off);
4122                         String found = c.match(text, pos);
4123                         if (found != null) {
4124                             return found;
4125                         }
4126                         break;
4127                     }
4128                     c = c.sibling;
4129                 } while (c != null);
4130             }
4131             pos.setIndex(off);
4132             return value;
4133         }
4134 
4135         protected String toKey(String k) {
4136             return k;
4137         }
4138 
4139         protected PrefixTree newNode(String k, String v, PrefixTree child) {
4140             return new PrefixTree(k, v, child);
4141         }
4142 
4143         protected boolean isEqual(char c1, char c2) {
4144             return c1 == c2;
4145         }
4146 
4147         protected boolean prefixOf(CharSequence text, int off, int end) {
4148             if (text instanceof String) {
4149                 return ((String)text).startsWith(key, off);
4150             }
4151             int len = key.length();
4152             if (len > end - off) {
4153                 return false;
4154             }
4155             int off0 = 0;
4156             while (len-- > 0) {
4157                 if (!isEqual(key.charAt(off0++), text.charAt(off++))) {
4158                     return false;
4159                 }
4160             }
4161             return true;
4162         }
4163 
4164         private int prefixLength(String k) {
4165             int off = 0;
4166             while (off < k.length() && off < key.length()) {
4167                 if (!isEqual(k.charAt(off), key.charAt(off))) {
4168                     return off;
4169                 }
4170                 off++;
4171             }
4172             return off;
4173         }
4174 
4175         /**
4176          * Case Insensitive prefix tree.
4177          */
4178         private static class CI extends PrefixTree {
4179 
4180             private CI(String k, String v, PrefixTree child) {
4181                 super(k, v, child);
4182             }
4183 
4184             @Override
4185             protected CI newNode(String k, String v, PrefixTree child) {
4186                 return new CI(k, v, child);
4187             }
4188 
4189             @Override
4190             protected boolean isEqual(char c1, char c2) {
4191                 return DateTimeParseContext.charEqualsIgnoreCase(c1, c2);
4192             }
4193 
4194             @Override
4195             protected boolean prefixOf(CharSequence text, int off, int end) {
4196                 int len = key.length();
4197                 if (len > end - off) {
4198                     return false;
4199                 }
4200                 int off0 = 0;
4201                 while (len-- > 0) {
4202                     if (!isEqual(key.charAt(off0++), text.charAt(off++))) {
4203                         return false;
4204                     }
4205                 }
4206                 return true;
4207             }
4208         }
4209 
4210         /**
4211          * Lenient prefix tree. Case insensitive and ignores characters
4212          * like space, underscore and slash.
4213          */
4214         private static class LENIENT extends CI {
4215 
4216             private LENIENT(String k, String v, PrefixTree child) {
4217                 super(k, v, child);
4218             }
4219 
4220             @Override
4221             protected CI newNode(String k, String v, PrefixTree child) {
4222                 return new LENIENT(k, v, child);
4223             }
4224 
4225             private boolean isLenientChar(char c) {
4226                 return c == ' ' || c == '_' || c == '/';
4227             }
4228 
4229             protected String toKey(String k) {
4230                 for (int i = 0; i < k.length(); i++) {
4231                     if (isLenientChar(k.charAt(i))) {
4232                         StringBuilder sb = new StringBuilder(k.length());
4233                         sb.append(k, 0, i);
4234                         i++;
4235                         while (i < k.length()) {
4236                             if (!isLenientChar(k.charAt(i))) {
4237                                 sb.append(k.charAt(i));
4238                             }
4239                             i++;
4240                         }
4241                         return sb.toString();
4242                     }
4243                 }
4244                 return k;
4245             }
4246 
4247             @Override
4248             public String match(CharSequence text, ParsePosition pos) {
4249                 int off = pos.getIndex();
4250                 int end = text.length();
4251                 int len = key.length();
4252                 int koff = 0;
4253                 while (koff < len && off < end) {
4254                     if (isLenientChar(text.charAt(off))) {
4255                         off++;
4256                         continue;
4257                     }
4258                     if (!isEqual(key.charAt(koff++), text.charAt(off++))) {
4259                         return null;
4260                     }
4261                 }
4262                 if (koff != len) {
4263                     return null;
4264                 }
4265                 if (child != null && off != end) {
4266                     int off0 = off;
4267                     while (off0 < end && isLenientChar(text.charAt(off0))) {
4268                         off0++;
4269                     }
4270                     if (off0 < end) {
4271                         PrefixTree c = child;
4272                         do {
4273                             if (isEqual(c.c0, text.charAt(off0))) {
4274                                 pos.setIndex(off0);
4275                                 String found = c.match(text, pos);
4276                                 if (found != null) {
4277                                     return found;
4278                                 }
4279                                 break;
4280                             }
4281                             c = c.sibling;
4282                         } while (c != null);
4283                     }
4284                 }
4285                 pos.setIndex(off);
4286                 return value;
4287             }
4288         }
4289     }
4290 
4291     //-----------------------------------------------------------------------
4292     /**
4293      * Prints or parses a chronology.
4294      */
4295     static final class ChronoPrinterParser implements DateTimePrinterParser {
4296         /** The text style to output, null means the ID. */
4297         private final TextStyle textStyle;
4298 
4299         ChronoPrinterParser(TextStyle textStyle) {
4300             // validated by caller
4301             this.textStyle = textStyle;
4302         }
4303 
4304         @Override
4305         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4306             Chronology chrono = context.getValue(TemporalQueries.chronology());
4307             if (chrono == null) {
4308                 return false;
4309             }
4310             if (textStyle == null) {
4311                 buf.append(chrono.getId());
4312             } else {
4313                 buf.append(getChronologyName(chrono, context.getLocale()));
4314             }
4315             return true;
4316         }
4317 
4318         @Override
4319         public int parse(DateTimeParseContext context, CharSequence text, int position) {
4320             // simple looping parser to find the chronology
4321             if (position < 0 || position > text.length()) {
4322                 throw new IndexOutOfBoundsException();
4323             }
4324             Set<Chronology> chronos = Chronology.getAvailableChronologies();
4325             Chronology bestMatch = null;
4326             int matchLen = -1;
4327             for (Chronology chrono : chronos) {
4328                 String name;
4329                 if (textStyle == null) {
4330                     name = chrono.getId();
4331                 } else {
4332                     name = getChronologyName(chrono, context.getLocale());
4333                 }
4334                 int nameLen = name.length();
4335                 if (nameLen > matchLen && context.subSequenceEquals(text, position, name, 0, nameLen)) {
4336                     bestMatch = chrono;
4337                     matchLen = nameLen;
4338                 }
4339             }
4340             if (bestMatch == null) {
4341                 return ~position;
4342             }
4343             context.setParsed(bestMatch);
4344             return position + matchLen;
4345         }
4346 
4347         /**
4348          * Returns the chronology name of the given chrono in the given locale
4349          * if available, or the chronology Id otherwise. The regular ResourceBundle
4350          * search path is used for looking up the chronology name.
4351          *
4352          * @param chrono  the chronology, not null
4353          * @param locale  the locale, not null
4354          * @return the chronology name of chrono in locale, or the id if no name is available
4355          * @throws NullPointerException if chrono or locale is null
4356          */
4357         private String getChronologyName(Chronology chrono, Locale locale) {
4358             String key = "calendarname." + chrono.getCalendarType();
4359             String name = DateTimeTextProvider.getLocalizedResource(key, locale);
4360             return Objects.requireNonNullElseGet(name, () -> chrono.getId());
4361         }
4362     }
4363 
4364     //-----------------------------------------------------------------------
4365     /**
4366      * Prints or parses a localized pattern.
4367      */
4368     static final class LocalizedPrinterParser implements DateTimePrinterParser {
4369         /** Cache of formatters. */
4370         private static final ConcurrentMap<String, DateTimeFormatter> FORMATTER_CACHE = new ConcurrentHashMap<>(16, 0.75f, 2);
4371 
4372         private final FormatStyle dateStyle;
4373         private final FormatStyle timeStyle;
4374 
4375         /**
4376          * Constructor.
4377          *
4378          * @param dateStyle  the date style to use, may be null
4379          * @param timeStyle  the time style to use, may be null
4380          */
4381         LocalizedPrinterParser(FormatStyle dateStyle, FormatStyle timeStyle) {
4382             // validated by caller
4383             this.dateStyle = dateStyle;
4384             this.timeStyle = timeStyle;
4385         }
4386 
4387         @Override
4388         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4389             Chronology chrono = Chronology.from(context.getTemporal());
4390             return formatter(context.getLocale(), chrono).toPrinterParser(false).format(context, buf);
4391         }
4392 
4393         @Override
4394         public int parse(DateTimeParseContext context, CharSequence text, int position) {
4395             Chronology chrono = context.getEffectiveChronology();
4396             return formatter(context.getLocale(), chrono).toPrinterParser(false).parse(context, text, position);
4397         }
4398 
4399         /**
4400          * Gets the formatter to use.
4401          * <p>
4402          * The formatter will be the most appropriate to use for the date and time style in the locale.
4403          * For example, some locales will use the month name while others will use the number.
4404          *
4405          * @param locale  the locale to use, not null
4406          * @param chrono  the chronology to use, not null
4407          * @return the formatter, not null
4408          * @throws IllegalArgumentException if the formatter cannot be found
4409          */
4410         private DateTimeFormatter formatter(Locale locale, Chronology chrono) {
4411             String key = chrono.getId() + '|' + locale.toString() + '|' + dateStyle + timeStyle;
4412             DateTimeFormatter formatter = FORMATTER_CACHE.get(key);
4413             if (formatter == null) {
4414                 String pattern = getLocalizedDateTimePattern(dateStyle, timeStyle, chrono, locale);
4415                 formatter = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(locale);
4416                 DateTimeFormatter old = FORMATTER_CACHE.putIfAbsent(key, formatter);
4417                 if (old != null) {
4418                     formatter = old;
4419                 }
4420             }
4421             return formatter;
4422         }
4423 
4424         @Override
4425         public String toString() {
4426             return "Localized(" + (dateStyle != null ? dateStyle : "") + "," +
4427                 (timeStyle != null ? timeStyle : "") + ")";
4428         }
4429     }
4430 
4431     //-----------------------------------------------------------------------
4432     /**
4433      * Prints or parses a localized pattern from a localized field.
4434      * The specific formatter and parameters is not selected until the
4435      * the field is to be printed or parsed.
4436      * The locale is needed to select the proper WeekFields from which
4437      * the field for day-of-week, week-of-month, or week-of-year is selected.
4438      */
4439     static final class WeekBasedFieldPrinterParser implements DateTimePrinterParser {
4440         private char chr;
4441         private int count;
4442 
4443         /**
4444          * Constructor.
4445          *
4446          * @param chr the pattern format letter that added this PrinterParser.
4447          * @param count the repeat count of the format letter
4448          */
4449         WeekBasedFieldPrinterParser(char chr, int count) {
4450             this.chr = chr;
4451             this.count = count;
4452         }
4453 
4454         @Override
4455         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4456             return printerParser(context.getLocale()).format(context, buf);
4457         }
4458 
4459         @Override
4460         public int parse(DateTimeParseContext context, CharSequence text, int position) {
4461             return printerParser(context.getLocale()).parse(context, text, position);
4462         }
4463 
4464         /**
4465          * Gets the printerParser to use based on the field and the locale.
4466          *
4467          * @param locale  the locale to use, not null
4468          * @return the formatter, not null
4469          * @throws IllegalArgumentException if the formatter cannot be found
4470          */
4471         private DateTimePrinterParser printerParser(Locale locale) {
4472             WeekFields weekDef = WeekFields.of(locale);
4473             TemporalField field = null;
4474             switch (chr) {
4475                 case 'Y':
4476                     field = weekDef.weekBasedYear();
4477                     if (count == 2) {
4478                         return new ReducedPrinterParser(field, 2, 2, 0, ReducedPrinterParser.BASE_DATE, 0);
4479                     } else {
4480                         return new NumberPrinterParser(field, count, 19,
4481                                 (count < 4) ? SignStyle.NORMAL : SignStyle.EXCEEDS_PAD, -1);
4482                     }
4483                 case 'e':
4484                 case 'c':
4485                     field = weekDef.dayOfWeek();
4486                     break;
4487                 case 'w':
4488                     field = weekDef.weekOfWeekBasedYear();
4489                     break;
4490                 case 'W':
4491                     field = weekDef.weekOfMonth();
4492                     break;
4493                 default:
4494                     throw new IllegalStateException("unreachable");
4495             }
4496             return new NumberPrinterParser(field, (count == 2 ? 2 : 1), 2, SignStyle.NOT_NEGATIVE);
4497         }
4498 
4499         @Override
4500         public String toString() {
4501             StringBuilder sb = new StringBuilder(30);
4502             sb.append("Localized(");
4503             if (chr == 'Y') {
4504                 if (count == 1) {
4505                     sb.append("WeekBasedYear");
4506                 } else if (count == 2) {
4507                     sb.append("ReducedValue(WeekBasedYear,2,2,2000-01-01)");
4508                 } else {
4509                     sb.append("WeekBasedYear,").append(count).append(",")
4510                             .append(19).append(",")
4511                             .append((count < 4) ? SignStyle.NORMAL : SignStyle.EXCEEDS_PAD);
4512                 }
4513             } else {
4514                 switch (chr) {
4515                     case 'c':
4516                     case 'e':
4517                         sb.append("DayOfWeek");
4518                         break;
4519                     case 'w':
4520                         sb.append("WeekOfWeekBasedYear");
4521                         break;
4522                     case 'W':
4523                         sb.append("WeekOfMonth");
4524                         break;
4525                     default:
4526                         break;
4527                 }
4528                 sb.append(",");
4529                 sb.append(count);
4530             }
4531             sb.append(")");
4532             return sb.toString();
4533         }
4534     }
4535 
4536     //-------------------------------------------------------------------------
4537     /**
4538      * Length comparator.
4539      */
4540     static final Comparator<String> LENGTH_SORT = new Comparator<String>() {
4541         @Override
4542         public int compare(String str1, String str2) {
4543             return str1.length() == str2.length() ? str1.compareTo(str2) : str1.length() - str2.length();
4544         }
4545     };
4546 }