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