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