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