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