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