src/share/classes/java/time/format/DateTimeFormatterBuilder.java

Print this page




  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.format.DateTimeTextProvider.LocaleStore;
  85 import java.time.temporal.Chrono;
  86 import java.time.temporal.ChronoField;
  87 import java.time.temporal.ISOChrono;
  88 import java.time.temporal.ISOFields;
  89 import java.time.temporal.Queries;
  90 import java.time.temporal.TemporalAccessor;
  91 import java.time.temporal.TemporalField;
  92 import java.time.temporal.TemporalQuery;
  93 import java.time.temporal.ValueRange;
  94 import java.time.temporal.WeekFields;
  95 import java.time.zone.ZoneRulesProvider;
  96 import java.util.AbstractMap.SimpleImmutableEntry;
  97 import java.util.ArrayList;
  98 import java.util.Arrays;
  99 import java.util.Collections;
 100 import java.util.Comparator;
 101 import java.util.HashMap;

 102 import java.util.Iterator;
 103 import java.util.LinkedHashMap;
 104 import java.util.List;
 105 import java.util.Locale;
 106 import java.util.Map;
 107 import java.util.Map.Entry;
 108 import java.util.Objects;
 109 import java.util.Set;
 110 import java.util.TimeZone;
 111 import java.util.concurrent.ConcurrentHashMap;
 112 
 113 import sun.util.locale.provider.TimeZoneNameUtility;
 114 
 115 /**
 116  * Builder to create date-time formatters.
 117  * <p>
 118  * This allows a {@code DateTimeFormatter} to be created.
 119  * All date-time formatters are created ultimately using this builder.
 120  * <p>
 121  * The basic elements of date-time can all be added:


 272      * Parsing can be strict or lenient - by default its strict.
 273      * This controls the degree of flexibility in matching the text and sign styles.
 274      * Applications calling this method should typically also call {@link #parseCaseInsensitive()}.
 275      * <p>
 276      * When used, this method changes the parsing to be lenient from this point onwards.
 277      * The change will remain in force until the end of the formatter that is eventually
 278      * constructed or until {@code parseStrict} is called.
 279      *
 280      * @return this, for chaining, not null
 281      */
 282     public DateTimeFormatterBuilder parseLenient() {
 283         appendInternal(SettingsParser.LENIENT);
 284         return this;
 285     }
 286 
 287     //-----------------------------------------------------------------------
 288     /**
 289      * Appends the value of a date-time field to the formatter using a normal
 290      * output style.
 291      * <p>
 292      * The value of the field will be output during a print.
 293      * If the value cannot be obtained then an exception will be thrown.
 294      * <p>
 295      * The value will be printed as per the normal print of an integer value.
 296      * Only negative numbers will be signed. No padding will be added.
 297      * <p>
 298      * The parser for a variable width value such as this normally behaves greedily,
 299      * requiring one digit, but accepting as many digits as possible.
 300      * This behavior can be affected by 'adjacent value parsing'.
 301      * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details.
 302      *
 303      * @param field  the field to append, not null
 304      * @return this, for chaining, not null
 305      */
 306     public DateTimeFormatterBuilder appendValue(TemporalField field) {
 307         Objects.requireNonNull(field, "field");
 308         active.valueParserIndex = appendInternal(new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL));
 309         return this;
 310     }
 311 
 312     /**
 313      * Appends the value of a date-time field to the formatter using a fixed
 314      * width, zero-padded approach.
 315      * <p>
 316      * The value of the field will be output during a print.
 317      * If the value cannot be obtained then an exception will be thrown.
 318      * <p>
 319      * The value will be zero-padded on the left. If the size of the value
 320      * means that it cannot be printed within the width then an exception is thrown.
 321      * If the value of the field is negative then an exception is thrown during printing.
 322      * <p>
 323      * This method supports a special technique of parsing known as 'adjacent value parsing'.
 324      * This technique solves the problem where a variable length value is followed by one or more
 325      * fixed length values. The standard parser is greedy, and thus it would normally
 326      * steal the digits that are needed by the fixed width value parsers that follow the
 327      * variable width one.
 328      * <p>
 329      * No action is required to initiate 'adjacent value parsing'.
 330      * When a call to {@code appendValue} with a variable width is made, the builder
 331      * enters adjacent value parsing setup mode. If the immediately subsequent method
 332      * call or calls on the same builder are to this method, then the parser will reserve
 333      * space so that the fixed width values can be parsed.
 334      * <p>
 335      * For example, consider {@code builder.appendValue(YEAR).appendValue(MONTH_OF_YEAR, 2);}
 336      * The year is a variable width parse of between 1 and 19 digits.
 337      * The month is a fixed width parse of 2 digits.
 338      * Because these were appended to the same builder immediately after one another,
 339      * the year parser will reserve two digits for the month to parse.
 340      * Thus, the text '201106' will correctly parse to a year of 2011 and a month of 6.
 341      * Without adjacent value parsing, the year would greedily parse all six digits and leave


 351      * If adjacent parsing is active, then parsing must match exactly the specified
 352      * number of digits in both strict and lenient modes.
 353      * In addition, no positive or negative sign is permitted.
 354      *
 355      * @param field  the field to append, not null
 356      * @param width  the width of the printed field, from 1 to 19
 357      * @return this, for chaining, not null
 358      * @throws IllegalArgumentException if the width is invalid
 359      */
 360     public DateTimeFormatterBuilder appendValue(TemporalField field, int width) {
 361         Objects.requireNonNull(field, "field");
 362         if (width < 1 || width > 19) {
 363             throw new IllegalArgumentException("The width must be from 1 to 19 inclusive but was " + width);
 364         }
 365         NumberPrinterParser pp = new NumberPrinterParser(field, width, width, SignStyle.NOT_NEGATIVE);
 366         return appendFixedWidth(width, pp);
 367     }
 368 
 369     /**
 370      * Appends the value of a date-time field to the formatter providing full
 371      * control over printing.
 372      * <p>
 373      * The value of the field will be output during a print.
 374      * If the value cannot be obtained then an exception will be thrown.
 375      * <p>
 376      * This method provides full control of the numeric formatting, including
 377      * zero-padding and the positive/negative sign.
 378      * <p>
 379      * The parser for a variable width value such as this normally behaves greedily,
 380      * accepting as many digits as possible.
 381      * This behavior can be affected by 'adjacent value parsing'.
 382      * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details.
 383      * <p>
 384      * In strict parsing mode, the minimum number of parsed digits is {@code minWidth}.
 385      * In lenient parsing mode, the minimum number of parsed digits is one.
 386      * <p>
 387      * If this method is invoked with equal minimum and maximum widths and a sign style of
 388      * {@code NOT_NEGATIVE} then it delegates to {@code appendValue(TemporalField,int)}.
 389      * In this scenario, the printing and parsing behavior described there occur.
 390      *
 391      * @param field  the field to append, not null
 392      * @param minWidth  the minimum field width of the printed field, from 1 to 19
 393      * @param maxWidth  the maximum field width of the printed field, from 1 to 19
 394      * @param signStyle  the positive/negative output style, not null
 395      * @return this, for chaining, not null
 396      * @throws IllegalArgumentException if the widths are invalid
 397      */
 398     public DateTimeFormatterBuilder appendValue(
 399             TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) {
 400         if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) {
 401             return appendValue(field, maxWidth);
 402         }
 403         Objects.requireNonNull(field, "field");
 404         Objects.requireNonNull(signStyle, "signStyle");
 405         if (minWidth < 1 || minWidth > 19) {
 406             throw new IllegalArgumentException("The minimum width must be from 1 to 19 inclusive but was " + minWidth);
 407         }
 408         if (maxWidth < 1 || maxWidth > 19) {
 409             throw new IllegalArgumentException("The maximum width must be from 1 to 19 inclusive but was " + maxWidth);
 410         }
 411         if (maxWidth < minWidth) {
 412             throw new IllegalArgumentException("The maximum width must exceed or equal the minimum width but " +
 413                     maxWidth + " < " + minWidth);
 414         }
 415         NumberPrinterParser pp = new NumberPrinterParser(field, minWidth, maxWidth, signStyle);
 416         if (minWidth == maxWidth) {
 417             appendInternal(pp);
 418         } else {
 419             active.valueParserIndex = appendInternal(pp);
 420         }
 421         return this;
 422     }
 423 
 424     //-----------------------------------------------------------------------
 425     /**
 426      * Appends the reduced value of a date-time field to the formatter.
 427      * <p>
 428      * This is typically used for printing and parsing a two digit year.
 429      * The {@code width} is the printed and parsed width.
 430      * The {@code baseValue} is used during parsing to determine the valid range.
 431      * <p>
 432      * For printing, the width is used to determine the number of characters to print.
 433      * The rightmost characters are output to match the width, left padding with zero.
 434      * <p>
 435      * For parsing, exactly the number of characters specified by the width are parsed.
 436      * This is incomplete information however, so the base value is used to complete the parse.
 437      * The base value is the first valid value in a range of ten to the power of width.
 438      * <p>
 439      * For example, a base value of {@code 1980} and a width of {@code 2} will have
 440      * valid values from {@code 1980} to {@code 2079}.
 441      * During parsing, the text {@code "12"} will result in the value {@code 2012} as that
 442      * is the value within the range where the last two digits are "12".
 443      * <p>
 444      * This is a fixed width parser operating using 'adjacent value parsing'.
 445      * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details.
 446      *
 447      * @param field  the field to append, not null
 448      * @param width  the width of the printed and parsed field, from 1 to 18
 449      * @param baseValue  the base value of the range of valid values
 450      * @return this, for chaining, not null
 451      * @throws IllegalArgumentException if the width or base value is invalid
 452      */


 508      *
 509      * @param field  the field to append, not null
 510      * @param minWidth  the minimum width of the field excluding the decimal point, from 0 to 9
 511      * @param maxWidth  the maximum width of the field excluding the decimal point, from 1 to 9
 512      * @param decimalPoint  whether to output the localized decimal point symbol
 513      * @return this, for chaining, not null
 514      * @throws IllegalArgumentException if the field has a variable set of valid values or
 515      *  either width is invalid
 516      */
 517     public DateTimeFormatterBuilder appendFraction(
 518             TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) {
 519         appendInternal(new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint));
 520         return this;
 521     }
 522 
 523     //-----------------------------------------------------------------------
 524     /**
 525      * Appends the text of a date-time field to the formatter using the full
 526      * text style.
 527      * <p>
 528      * The text of the field will be output during a print.
 529      * The value must be within the valid range of the field.
 530      * If the value cannot be obtained then an exception will be thrown.
 531      * If the field has no textual representation, then the numeric value will be used.
 532      * <p>
 533      * The value will be printed as per the normal print of an integer value.
 534      * Only negative numbers will be signed. No padding will be added.
 535      *
 536      * @param field  the field to append, not null
 537      * @return this, for chaining, not null
 538      */
 539     public DateTimeFormatterBuilder appendText(TemporalField field) {
 540         return appendText(field, TextStyle.FULL);
 541     }
 542 
 543     /**
 544      * Appends the text of a date-time field to the formatter.
 545      * <p>
 546      * The text of the field will be output during a print.
 547      * The value must be within the valid range of the field.
 548      * If the value cannot be obtained then an exception will be thrown.
 549      * If the field has no textual representation, then the numeric value will be used.
 550      * <p>
 551      * The value will be printed as per the normal print of an integer value.
 552      * Only negative numbers will be signed. No padding will be added.
 553      *
 554      * @param field  the field to append, not null
 555      * @param textStyle  the text style to use, not null
 556      * @return this, for chaining, not null
 557      */
 558     public DateTimeFormatterBuilder appendText(TemporalField field, TextStyle textStyle) {
 559         Objects.requireNonNull(field, "field");
 560         Objects.requireNonNull(textStyle, "textStyle");
 561         appendInternal(new TextPrinterParser(field, textStyle, DateTimeTextProvider.getInstance()));
 562         return this;
 563     }
 564 
 565     /**
 566      * Appends the text of a date-time field to the formatter using the specified
 567      * map to supply the text.
 568      * <p>
 569      * The standard text outputting methods use the localized text in the JDK.
 570      * This method allows that text to be specified directly.
 571      * The supplied map is not validated by the builder to ensure that printing or
 572      * parsing is possible, thus an invalid map may throw an error during later use.
 573      * <p>
 574      * Supplying the map of text provides considerable flexibility in printing and parsing.
 575      * For example, a legacy application might require or supply the months of the
 576      * year as "JNY", "FBY", "MCH" etc. These do not match the standard set of text
 577      * for localized month names. Using this method, a map can be created which
 578      * defines the connection between each value and the text:
 579      * <pre>
 580      * Map&lt;Long, String&gt; map = new HashMap&lt;&gt;();
 581      * map.put(1, "JNY");
 582      * map.put(2, "FBY");
 583      * map.put(3, "MCH");
 584      * ...
 585      * builder.appendText(MONTH_OF_YEAR, map);
 586      * </pre>
 587      * <p>
 588      * Other uses might be to output the value with a suffix, such as "1st", "2nd", "3rd",
 589      * or as Roman numerals "I", "II", "III", "IV".
 590      * <p>
 591      * During printing, the value is obtained and checked that it is in the valid range.
 592      * If text is not available for the value then it is output as a number.
 593      * During parsing, the parser will match against the map of text and numeric values.
 594      *
 595      * @param field  the field to append, not null
 596      * @param textLookup  the map from the value to the text
 597      * @return this, for chaining, not null
 598      */
 599     public DateTimeFormatterBuilder appendText(TemporalField field, Map<Long, String> textLookup) {
 600         Objects.requireNonNull(field, "field");
 601         Objects.requireNonNull(textLookup, "textLookup");
 602         Map<Long, String> copy = new LinkedHashMap<>(textLookup);
 603         Map<TextStyle, Map<Long, String>> map = Collections.singletonMap(TextStyle.FULL, copy);
 604         final LocaleStore store = new LocaleStore(map);
 605         DateTimeTextProvider provider = new DateTimeTextProvider() {
 606             @Override
 607             public String getText(TemporalField field, long value, TextStyle style, Locale locale) {
 608                 return store.getText(value, style);
 609             }
 610             @Override
 611             public Iterator<Entry<String, Long>> getTextIterator(TemporalField field, TextStyle style, Locale locale) {
 612                 return store.getTextIterator(style);
 613             }
 614         };
 615         appendInternal(new TextPrinterParser(field, TextStyle.FULL, provider));
 616         return this;
 617     }
 618 
 619     //-----------------------------------------------------------------------
 620     /**
 621      * Appends an instant using ISO-8601 to the formatter.
 622      * <p>
 623      * Instants have a fixed output format.
 624      * They are converted to a date-time with a zone-offset of UTC and printed
 625      * using the standard ISO-8601 format.
 626      * <p>
 627      * An alternative to this method is to print/parse the instant as a single
 628      * epoch-seconds value. That is achieved using {@code appendValue(INSTANT_SECONDS)}.
 629      *
 630      * @return this, for chaining, not null
 631      */
 632     public DateTimeFormatterBuilder appendInstant() {
 633         appendInternal(new InstantPrinterParser());
 634         return this;
 635     }
 636 
 637     /**
 638      * Appends the zone offset, such as '+01:00', to the formatter.
 639      * <p>
 640      * This appends an instruction to print/parse the offset ID to the builder.
 641      * This is equivalent to calling {@code appendOffset("HH:MM:ss", "Z")}.
 642      *
 643      * @return this, for chaining, not null
 644      */
 645     public DateTimeFormatterBuilder appendOffsetId() {
 646         appendInternal(OffsetIdPrinterParser.INSTANCE_ID);
 647         return this;
 648     }
 649 
 650     /**
 651      * Appends the zone offset, such as '+01:00', to the formatter.
 652      * <p>
 653      * This appends an instruction to print/parse the offset ID to the builder.
 654      * <p>
 655      * During printing, the offset is obtained using a mechanism equivalent
 656      * to querying the temporal with {@link Queries#offset()}.
 657      * It will be printed using the format defined below.
 658      * If the offset cannot be obtained then an exception is thrown unless the
 659      * section of the formatter is optional.
 660      * <p>
 661      * During parsing, the offset is parsed using the format defined below.
 662      * If the offset cannot be parsed then an exception is thrown unless the
 663      * section of the formatter is optional.
 664      * <p>
 665      * The format of the offset is controlled by a pattern which must be one
 666      * of the following:
 667      * <p><ul>
 668      * <li>{@code +HH} - hour only, ignoring any minute
 669      * <li>{@code +HHMM} - hour and minute, no colon
 670      * <li>{@code +HH:MM} - hour and minute, with colon
 671      * <li>{@code +HHMMss} - hour and minute, with second if non-zero and no colon
 672      * <li>{@code +HH:MM:ss} - hour and minute, with second if non-zero and colon


 673      * <li>{@code +HHMMSS} - hour, minute and second, no colon
 674      * <li>{@code +HH:MM:SS} - hour, minute and second, with colon
 675      * </ul><p>
 676      * The "no offset" text controls what text is printed when the offset is zero.

 677      * Example values would be 'Z', '+00:00', 'UTC' or 'GMT'.
 678      * Three formats are accepted for parsing UTC - the "no offset" text, and the
 679      * plus and minus versions of zero defined by the pattern.
 680      *
 681      * @param pattern  the pattern to use, not null
 682      * @param noOffsetText  the text to use when the offset is zero, not null
 683      * @return this, for chaining, not null
 684      */
 685     public DateTimeFormatterBuilder appendOffset(String pattern, String noOffsetText) {
 686         appendInternal(new OffsetIdPrinterParser(noOffsetText, pattern));
 687         return this;
 688     }
 689 
 690     //-----------------------------------------------------------------------
 691     /**
 692      * Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to the formatter.
 693      * <p>
 694      * This appends an instruction to print/parse the zone ID to the builder.
 695      * The zone ID is obtained in a strict manner suitable for {@code ZonedDateTime}.
 696      * By contrast, {@code OffsetDateTime} does not have a zone ID suitable
 697      * for use with this method, see {@link #appendZoneOrOffsetId()}.
 698      * <p>
 699      * During printing, the zone is obtained using a mechanism equivalent
 700      * to querying the temporal with {@link Queries#zoneId()}.
 701      * It will be printed using the result of {@link ZoneId#getId()}.
 702      * If the zone cannot be obtained then an exception is thrown unless the
 703      * section of the formatter is optional.
 704      * <p>
 705      * During parsing, the zone is parsed and must match a known zone or offset.
 706      * If the zone cannot be parsed then an exception is thrown unless the
 707      * section of the formatter is optional.




























 708      *
 709      * @return this, for chaining, not null
 710      * @see #appendZoneRegionId()
 711      */
 712     public DateTimeFormatterBuilder appendZoneId() {
 713         appendInternal(new ZoneIdPrinterParser(Queries.zoneId(), "ZoneId()"));
 714         return this;
 715     }
 716 
 717     /**
 718      * Appends the time-zone region ID, such as 'Europe/Paris', to the formatter,
 719      * rejecting the zone ID if it is a {@code ZoneOffset}.
 720      * <p>
 721      * This appends an instruction to print/parse the zone ID to the builder
 722      * only if it is a region-based ID.
 723      * <p>
 724      * During printing, the zone is obtained using a mechanism equivalent
 725      * to querying the temporal with {@link Queries#zoneId()}.
 726      * If the zone is a {@code ZoneOffset} or it cannot be obtained then
 727      * an exception is thrown unless the section of the formatter is optional.
 728      * If the zone is not an offset, then the zone will be printed using
 729      * the zone ID from {@link ZoneId#getId()}.
 730      * <p>
 731      * During parsing, the zone is parsed and must match a known zone or offset.
 732      * If the zone cannot be parsed then an exception is thrown unless the
 733      * section of the formatter is optional.
 734      * Note that parsing accepts offsets, whereas printing will never produce
 735      * one, thus parsing is equivalent to {@code appendZoneId}.































 736      *
 737      * @return this, for chaining, not null
 738      * @see #appendZoneId()
 739      */
 740     public DateTimeFormatterBuilder appendZoneRegionId() {
 741         appendInternal(new ZoneIdPrinterParser(QUERY_REGION_ONLY, "ZoneRegionId()"));
 742         return this;
 743     }
 744 
 745     /**
 746      * Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to
 747      * the formatter, using the best available zone ID.
 748      * <p>
 749      * This appends an instruction to print/parse the best available
 750      * zone or offset ID to the builder.
 751      * The zone ID is obtained in a lenient manner that first attempts to
 752      * find a true zone ID, such as that on {@code ZonedDateTime}, and
 753      * then attempts to find an offset, such as that on {@code OffsetDateTime}.
 754      * <p>
 755      * During printing, the zone is obtained using a mechanism equivalent
 756      * to querying the temporal with {@link Queries#zone()}.
 757      * It will be printed using the result of {@link ZoneId#getId()}.
 758      * If the zone cannot be obtained then an exception is thrown unless the
 759      * section of the formatter is optional.
 760      * <p>
 761      * During parsing, the zone is parsed and must match a known zone or offset.
 762      * If the zone cannot be parsed then an exception is thrown unless the
 763      * section of the formatter is optional.




























 764      * <p>
 765      * This method is is identical to {@code appendZoneId()} except in the
 766      * mechanism used to obtain the zone.
 767      *
 768      * @return this, for chaining, not null
 769      * @see #appendZoneId()
 770      */
 771     public DateTimeFormatterBuilder appendZoneOrOffsetId() {
 772         appendInternal(new ZoneIdPrinterParser(Queries.zone(), "ZoneOrOffsetId()"));
 773         return this;
 774     }
 775 
 776     /**
 777      * Appends the time-zone name, such as 'British Summer Time', to the formatter.
 778      * <p>
 779      * This appends an instruction to print the textual name of the zone to the builder.

 780      * <p>
 781      * During printing, the zone is obtained using a mechanism equivalent
 782      * to querying the temporal with {@link Queries#zoneId()}.
 783      * If the zone is a {@code ZoneOffset} it will be printed using the
 784      * result of {@link ZoneOffset#getId()}.
 785      * If the zone is not an offset, the textual name will be looked up
 786      * for the locale set in the {@link DateTimeFormatter}.
 787      * If the temporal object being printed represents an instant, then the text
 788      * will be the summer or winter time text as appropriate.
 789      * If the lookup for text does not find any suitable reuslt, then the
 790      * {@link ZoneId#getId() ID} will be printed instead.
 791      * If the zone cannot be obtained then an exception is thrown unless the
 792      * section of the formatter is optional.
 793      * <p>
 794      * Parsing is not currently supported.







 795      *
 796      * @param textStyle  the text style to use, not null
 797      * @return this, for chaining, not null
 798      */
 799     public DateTimeFormatterBuilder appendZoneText(TextStyle textStyle) {
 800         // TODO: parsing of zone text?
 801 //        * During parsing, either the textual zone name, the zone ID or the offset
 802 //        * is accepted.
 803 //        * If the zone cannot be parsed then an exception is thrown unless the
 804 //        * section of the formatter is optional.
 805         appendInternal(new ZoneTextPrinterParser(textStyle));






































 806         return this;
 807     }
 808 
 809     //-----------------------------------------------------------------------
 810     /**
 811      * Appends the chronology ID to the formatter.
 812      * <p>
 813      * The chronology ID will be output during a print.
 814      * If the chronology cannot be obtained then an exception will be thrown.











 815      *
 816      * @return this, for chaining, not null
 817      */
 818     public DateTimeFormatterBuilder appendChronoId() {
 819         appendInternal(new ChronoPrinterParser(null));
 820         return this;
 821     }
 822 
 823     /**
 824      * Appends the chronology name to the formatter.
 825      * <p>
 826      * The calendar system name will be output during a print.
 827      * If the chronology cannot be obtained then an exception will be thrown.
 828      * The calendar system name is obtained from the formatting symbols.
 829      *
 830      * @param textStyle  the text style to use, not null
 831      * @return this, for chaining, not null
 832      */
 833     public DateTimeFormatterBuilder appendChronoText(TextStyle textStyle) {
 834         Objects.requireNonNull(textStyle, "textStyle");
 835         appendInternal(new ChronoPrinterParser(textStyle));
 836         return this;
 837     }
 838 
 839     //-----------------------------------------------------------------------
 840     /**
 841      * Appends a localized date-time pattern to the formatter.
 842      * <p>
 843      * The pattern is resolved lazily using the locale being used during the print/parse
 844      * (stored in {@link DateTimeFormatter}.














 845      * <p>
 846      * The pattern can vary by chronology, although typically it doesn't.
 847      * This method uses the standard ISO chronology patterns.
 848      *
 849      * @param dateStyle  the date style to use, null means no date required
 850      * @param timeStyle  the time style to use, null means no time required
 851      * @return this, for chaining, not null

 852      */
 853     public DateTimeFormatterBuilder appendLocalized(FormatStyle dateStyle, FormatStyle timeStyle) {
 854         return appendLocalized(dateStyle, timeStyle, ISOChrono.INSTANCE);
 855     }
 856 
 857     /**
 858      * Appends a localized date-time pattern to the formatter.
 859      * <p>
 860      * The pattern is resolved lazily using the locale being used during the print/parse,
 861      * stored in {@link DateTimeFormatter}.
 862      * <p>
 863      * The pattern can vary by chronology, although typically it doesn't.
 864      * This method allows the chronology to be specified.
 865      *
 866      * @param dateStyle  the date style to use, null means no date required
 867      * @param timeStyle  the time style to use, null means no time required
 868      * @param chrono  the chronology to use, not null
 869      * @return this, for chaining, not null
 870      */
 871     public DateTimeFormatterBuilder appendLocalized(FormatStyle dateStyle, FormatStyle timeStyle, Chrono<?> chrono) {
 872         Objects.requireNonNull(chrono, "chrono");
 873         if (dateStyle != null || timeStyle != null) {
 874             appendInternal(new LocalizedPrinterParser(dateStyle, timeStyle, chrono));
 875         }

 876         return this;
 877     }
 878 
 879     //-----------------------------------------------------------------------
 880     /**
 881      * Appends a character literal to the formatter.
 882      * <p>
 883      * This character will be output during a print.
 884      *
 885      * @param literal  the literal to append, not null
 886      * @return this, for chaining, not null
 887      */
 888     public DateTimeFormatterBuilder appendLiteral(char literal) {
 889         appendInternal(new CharLiteralPrinterParser(literal));
 890         return this;
 891     }
 892 
 893     /**
 894      * Appends a string literal to the formatter.
 895      * <p>
 896      * This string will be output during a print.
 897      * <p>
 898      * If the literal is empty, nothing is added to the formatter.
 899      *
 900      * @param literal  the literal to append, not null
 901      * @return this, for chaining, not null
 902      */
 903     public DateTimeFormatterBuilder appendLiteral(String literal) {
 904         Objects.requireNonNull(literal, "literal");
 905         if (literal.length() > 0) {
 906             if (literal.length() == 1) {
 907                 appendInternal(new CharLiteralPrinterParser(literal.charAt(0)));
 908             } else {
 909                 appendInternal(new StringLiteralPrinterParser(literal));
 910             }
 911         }
 912         return this;
 913     }
 914 
 915     //-----------------------------------------------------------------------
 916     /**
 917      * Appends all the elements of a formatter to the builder.
 918      * <p>
 919      * This method has the same effect as appending each of the constituent
 920      * parts of the formatter directly to this builder.
 921      *
 922      * @param formatter  the formatter to add, not null
 923      * @return this, for chaining, not null
 924      */
 925     public DateTimeFormatterBuilder append(DateTimeFormatter formatter) {
 926         Objects.requireNonNull(formatter, "formatter");
 927         appendInternal(formatter.toPrinterParser(false));
 928         return this;
 929     }
 930 
 931     /**
 932      * Appends a formatter to the builder which will optionally print/parse.
 933      * <p>
 934      * This method has the same effect as appending each of the constituent
 935      * parts directly to this builder surrounded by an {@link #optionalStart()} and
 936      * {@link #optionalEnd()}.
 937      * <p>
 938      * The formatter will print if data is available for all the fields contained within it.
 939      * The formatter will parse if the string matches, otherwise no error is returned.
 940      *
 941      * @param formatter  the formatter to add, not null
 942      * @return this, for chaining, not null
 943      */
 944     public DateTimeFormatterBuilder appendOptional(DateTimeFormatter formatter) {
 945         Objects.requireNonNull(formatter, "formatter");
 946         appendInternal(formatter.toPrinterParser(true));
 947         return this;
 948     }
 949 
 950     //-----------------------------------------------------------------------
 951     /**
 952      * Appends the elements defined by the specified pattern to the builder.
 953      * <p>
 954      * All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters.
 955      * The characters '{' and '}' are reserved for future use.
 956      * The characters '[' and ']' indicate optional patterns.
 957      * The following pattern letters are defined:
 958      * <pre>
 959      *  Symbol  Meaning                     Presentation      Examples
 960      *  ------  -------                     ------------      -------
 961      *   G       era                         number/text       1; 01; AD; Anno Domini
 962      *   y       year                        year              2004; 04
 963      *   D       day-of-year                 number            189
 964      *   M       month-of-year               number/text       7; 07; Jul; July; J
 965      *   d       day-of-month                number            10
 966      *
 967      *   Q       quarter-of-year             number/text       3; 03; Q3
 968      *   Y       week-based-year             year              1996; 96
 969      *   w       week-of-year                number            27
 970      *   W       week-of-month               number            27
 971      *   e       localized day-of-week       number            2; Tue; Tuesday; T
 972      *   E       day-of-week                 number/text       2; Tue; Tuesday; T
 973      *   F       week-of-month               number            3
 974      *
 975      *   a       am-pm-of-day                text              PM
 976      *   h       clock-hour-of-am-pm (1-12)  number            12
 977      *   K       hour-of-am-pm (0-11)        number            0
 978      *   k       clock-hour-of-am-pm (1-24)  number            0
 979      *
 980      *   H       hour-of-day (0-23)          number            0
 981      *   m       minute-of-hour              number            30
 982      *   s       second-of-minute            number            55
 983      *   S       fraction-of-second          fraction          978
 984      *   A       milli-of-day                number            1234
 985      *   n       nano-of-second              number            987654321
 986      *   N       nano-of-day                 number            1234000000
 987      *
 988      *   I       time-zone ID                zoneId            America/Los_Angeles
 989      *   z       time-zone name              text              Pacific Standard Time; PST
 990      *   Z       zone-offset                 offset-Z          +0000; -0800; -08:00;
 991      *   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;


 992      *
 993      *   p       pad next                    pad modifier      1
 994      *
 995      *   '       escape for text             delimiter
 996      *   ''      single quote                literal           '
 997      *   [       optional section start
 998      *   ]       optional section end
 999      *   {}      reserved for future use
1000      * </pre>
1001      * <p>
1002      * The count of pattern letters determine the format.
1003      * <p>
1004      * <b>Text</b>: The text style is determined based on the number of pattern letters used.
1005      * Less than 4 pattern letters will use the {@link TextStyle#SHORT short form}.
1006      * Exactly 4 pattern letters will use the {@link TextStyle#FULL full form}.
1007      * Exactly 5 pattern letters will use the {@link TextStyle#NARROW narrow form}.
1008      * <p>
1009      * <b>Number</b>: If the count of letters is one, then the value is printed using the minimum number
1010      * of digits and without padding as per {@link #appendValue(java.time.temporal.TemporalField)}. Otherwise, the
1011      * count of digits is used as the width of the output field as per {@link #appendValue(java.time.temporal.TemporalField, int)}.
1012      * <p>
1013      * <b>Number/Text</b>: If the count of pattern letters is 3 or greater, use the Text rules above.
1014      * Otherwise use the Number rules above.
1015      * <p>
1016      * <b>Fraction</b>: Outputs the nano-of-second field as a fraction-of-second.
1017      * The nano-of-second value has nine digits, thus the count of pattern letters is from 1 to 9.
1018      * If it is less than 9, then the nano-of-second value is truncated, with only the most
1019      * significant digits being output.
1020      * When parsing in strict mode, the number of parsed digits must match the count of pattern letters.
1021      * When parsing in lenient mode, the number of parsed digits must be at least the count of pattern
1022      * letters, up to 9 digits.
1023      * <p>
1024      * <b>Year</b>: The count of letters determines the minimum field width below which padding is used.
1025      * If the count of letters is two, then a {@link #appendValueReduced reduced} two digit form is used.
1026      * For printing, this outputs the rightmost two digits. For parsing, this will parse using the
1027      * base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.
1028      * If the count of letters is less than four (but not two), then the sign is only output for negative
1029      * years as per {@link SignStyle#NORMAL}.
1030      * Otherwise, the sign is output if the pad width is exceeded, as per {@link SignStyle#EXCEEDS_PAD}
1031      * <p>
1032      * <b>ZoneId</b>: 'I' outputs the zone ID, such as 'Europe/Paris'.


















1033      * <p>
1034      * <b>Offset X</b>: This formats the offset using 'Z' when the offset is zero.
1035      * One letter outputs just the hour', such as '+01'

1036      * Two letters outputs the hour and minute, without a colon, such as '+0130'.
1037      * Three letters outputs the hour and minute, with a colon, such as '+01:30'.
1038      * Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'.
1039      * Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'.
















1040      * <p>
1041      * <b>Offset Z</b>: This formats the offset using '+0000' or '+00:00' when the offset is zero.
1042      * One or two letters outputs the hour and minute, without a colon, such as '+0130'.
1043      * Three letters outputs the hour and minute, with a colon, such as '+01:30'.
1044      * <p>
1045      * <b>Zone names</b>: Time zone names ('z') cannot be parsed.





1046      * <p>
1047      * <b>Optional section</b>: The optional section markers work exactly like calling {@link #optionalStart()}
1048      * and {@link #optionalEnd()}.
1049      * <p>
1050      * <b>Pad modifier</b>: Modifies the pattern that immediately follows to be padded with spaces.
1051      * The pad width is determined by the number of pattern letters.
1052      * This is the same as calling {@link #padNext(int)}.
1053      * <p>
1054      * For example, 'ppH' outputs the hour-of-day padded on the left with spaces to a width of 2.
1055      * <p>
1056      * Any unrecognized letter is an error.
1057      * Any non-letter character, other than '[', ']', '{', '}' and the single quote will be output directly.
1058      * Despite this, it is recommended to use single quotes around all characters that you want to
1059      * output directly to ensure that future changes do not break your application.
1060      * <p>
1061      * The pattern string is similar, but not identical, to {@link java.text.SimpleDateFormat SimpleDateFormat}.



1062      * Pattern letters 'E' and 'u' are merged, which changes the meaning of "E" and "EE" to be numeric.
1063      * Pattern letters 'Z' and 'X' are extended.
1064      * Pattern letter 'y' and 'Y' parse years of two digits and more than 4 digits differently.
1065      * Pattern letters 'n', 'A', 'N', 'I' and 'p' are added.
1066      * Number types will reject large numbers.
1067      * The pattern string is also similar, but not identical, to that defined by the
1068      * Unicode Common Locale Data Repository (CLDR).
1069      *
1070      * @param pattern  the pattern to add, not null
1071      * @return this, for chaining, not null
1072      * @throws IllegalArgumentException if the pattern is invalid
1073      */
1074     public DateTimeFormatterBuilder appendPattern(String pattern) {
1075         Objects.requireNonNull(pattern, "pattern");
1076         parsePattern(pattern);
1077         return this;
1078     }
1079 
1080     private void parsePattern(String pattern) {
1081         for (int pos = 0; pos < pattern.length(); pos++) {
1082             char cur = pattern.charAt(pos);
1083             if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) {
1084                 int start = pos++;
1085                 for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++);  // short loop
1086                 int count = pos - start;
1087                 // padding
1088                 if (cur == 'p') {


1090                     if (pos < pattern.length()) {
1091                         cur = pattern.charAt(pos);
1092                         if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) {
1093                             pad = count;
1094                             start = pos++;
1095                             for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++);  // short loop
1096                             count = pos - start;
1097                         }
1098                     }
1099                     if (pad == 0) {
1100                         throw new IllegalArgumentException(
1101                                 "Pad letter 'p' must be followed by valid pad pattern: " + pattern);
1102                     }
1103                     padNext(pad); // pad and continue parsing
1104                 }
1105                 // main rules
1106                 TemporalField field = FIELD_MAP.get(cur);
1107                 if (field != null) {
1108                     parseField(cur, count, field);
1109                 } else if (cur == 'z') {
1110                     if (count < 4) {
1111                         appendZoneText(TextStyle.SHORT);
1112                     } else {
1113                         appendZoneText(TextStyle.FULL);






1114                     }
1115                 } else if (cur == 'I') {
1116                     appendZoneId();
1117                 } else if (cur == 'Z') {
1118                     if (count > 3) {
1119                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1120                     }
1121                     if (count < 3) {
1122                         appendOffset("+HHMM", "+0000");
1123                     } else {
1124                         appendOffset("+HH:MM", "+00:00");
1125                     }
1126                 } else if (cur == 'X') {
1127                     if (count > 5) {
1128                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1129                     }
1130                     appendOffset(OffsetIdPrinterParser.PATTERNS[count - 1], "Z");






1131                 } else if (cur == 'w' || cur == 'e') {
1132                     // Fields defined by Locale
1133                     if (count > 1) {
1134                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1135                     }
1136                     appendInternal(new WeekBasedFieldPrinterParser(cur, count));
1137                 } else if (cur == 'W') {
1138                     // Fields defined by Locale
1139                     if (count > 2) {
1140                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1141                     }
1142                     appendInternal(new WeekBasedFieldPrinterParser(cur, count));
1143                 } else {
1144                     throw new IllegalArgumentException("Unknown pattern letter: " + cur);
1145                 }
1146                 pos--;
1147 
1148             } else if (cur == '\'') {
1149                 // parse literals
1150                 int start = pos++;


1179             } else if (cur == '{' || cur == '}') {
1180                 throw new IllegalArgumentException("Pattern includes reserved character: '" + cur + "'");
1181             } else {
1182                 appendLiteral(cur);
1183             }
1184         }
1185     }
1186 
1187     private void parseField(char cur, int count, TemporalField field) {
1188         switch (cur) {
1189             case 'y':
1190             case 'Y':
1191                 if (count == 2) {
1192                     appendValueReduced(field, 2, 2000);
1193                 } else if (count < 4) {
1194                     appendValue(field, count, 19, SignStyle.NORMAL);
1195                 } else {
1196                     appendValue(field, count, 19, SignStyle.EXCEEDS_PAD);
1197                 }
1198                 break;
1199             case 'G':
1200             case 'M':
1201             case 'Q':
1202             case 'E':
1203                 switch (count) {
1204                     case 1:
1205                         appendValue(field);
1206                         break;
1207                     case 2:
1208                         appendValue(field, 2);
1209                         break;
1210                     case 3:
1211                         appendText(field, TextStyle.SHORT);
1212                         break;
1213                     case 4:
1214                         appendText(field, TextStyle.FULL);
1215                         break;
1216                     case 5:
1217                         appendText(field, TextStyle.NARROW);
1218                         break;
1219                     default:
1220                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1221                 }
1222                 break;

1223             case 'a':
1224                 switch (count) {
1225                     case 1:
1226                     case 2:
1227                     case 3:
1228                         appendText(field, TextStyle.SHORT);
1229                         break;
1230                     case 4:
1231                         appendText(field, TextStyle.FULL);
1232                         break;
1233                     case 5:
1234                         appendText(field, TextStyle.NARROW);
1235                         break;
1236                     default:
1237                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1238                 }
1239                 break;
1240             case 'S':
1241                 appendFraction(NANO_OF_SECOND, count, count, false);
1242                 break;
1243             default:
1244                 if (count == 1) {
1245                     appendValue(field);
1246                 } else {
1247                     appendValue(field, count);
1248                 }
1249                 break;
1250         }
1251     }
1252 
1253     /** Map of letters to fields. */
1254     private static final Map<Character, TemporalField> FIELD_MAP = new HashMap<>();
1255     static {
1256         FIELD_MAP.put('G', ChronoField.ERA);                       // Java, CLDR (different to both for 1/2 chars)
1257         FIELD_MAP.put('y', ChronoField.YEAR);                      // CLDR
1258         // FIELD_MAP.put('y', ChronoField.YEAR_OF_ERA);            // Java, CLDR  // TODO redefine from above
1259         // FIELD_MAP.put('u', ChronoField.YEAR);                   // CLDR  // TODO
1260         // FIELD_MAP.put('Y', ISODateTimeField.WEEK_BASED_YEAR);          // Java7, CLDR (needs localized week number)  // TODO
1261         FIELD_MAP.put('Q', ISOFields.QUARTER_OF_YEAR);             // CLDR (removed quarter from 310)
1262         FIELD_MAP.put('M', ChronoField.MONTH_OF_YEAR);             // Java, CLDR
1263         // FIELD_MAP.put('w', WeekFields.weekOfYear());            // Java, CLDR (needs localized week number)
1264         // FIELD_MAP.put('W', WeekFields.weekOfMonth());           // Java, CLDR (needs localized week number)
1265         FIELD_MAP.put('D', ChronoField.DAY_OF_YEAR);               // Java, CLDR
1266         FIELD_MAP.put('d', ChronoField.DAY_OF_MONTH);              // Java, CLDR
1267         FIELD_MAP.put('F', ChronoField.ALIGNED_WEEK_OF_MONTH);     // Java, CLDR
1268         FIELD_MAP.put('E', ChronoField.DAY_OF_WEEK);               // Java, CLDR (different to both for 1/2 chars)
1269         // FIELD_MAP.put('e', WeekFields.dayOfWeek());             // CLDR (needs localized week number)
1270         FIELD_MAP.put('a', ChronoField.AMPM_OF_DAY);               // Java, CLDR
1271         FIELD_MAP.put('H', ChronoField.HOUR_OF_DAY);               // Java, CLDR
1272         FIELD_MAP.put('k', ChronoField.CLOCK_HOUR_OF_DAY);         // Java, CLDR
1273         FIELD_MAP.put('K', ChronoField.HOUR_OF_AMPM);              // Java, CLDR
1274         FIELD_MAP.put('h', ChronoField.CLOCK_HOUR_OF_AMPM);        // Java, CLDR
1275         FIELD_MAP.put('m', ChronoField.MINUTE_OF_HOUR);            // Java, CLDR
1276         FIELD_MAP.put('s', ChronoField.SECOND_OF_MINUTE);          // Java, CLDR
1277         FIELD_MAP.put('S', ChronoField.NANO_OF_SECOND);            // CLDR (Java uses milli-of-second number)
1278         FIELD_MAP.put('A', ChronoField.MILLI_OF_DAY);              // CLDR
1279         FIELD_MAP.put('n', ChronoField.NANO_OF_SECOND);            // 310
1280         FIELD_MAP.put('N', ChronoField.NANO_OF_DAY);               // 310
1281         // reserved - z,Z,X,I,p
1282         // Java - X - compatible, but extended to 4 and 5 letters
1283         // Java - u - clashes with CLDR, go with CLDR (year-proleptic) here
1284         // CLDR - U - cycle year name, not supported by 310 yet
1285         // CLDR - l - deprecated
1286         // CLDR - j - not relevant
1287         // CLDR - g - modified-julian-day
1288         // CLDR - z - time-zone names  // TODO properly
1289         // CLDR - Z - different approach here  // TODO bring 310 in line with CLDR
1290         // CLDR - v,V - extended time-zone names
1291         // CLDR - q/c/L - standalone quarter/day-of-week/month
1292         //  310 - I - time-zone id
1293         //  310 - p - prefix for padding









1294     }
1295 
1296     //-----------------------------------------------------------------------
1297     /**
1298      * Causes the next added printer/parser to pad to a fixed width using a space.
1299      * <p>
1300      * This padding will pad to a fixed width using spaces.
1301      * <p>
1302      * An exception will be thrown during printing if the pad width
1303      * is exceeded.







1304      *
1305      * @param padWidth  the pad width, 1 or greater
1306      * @return this, for chaining, not null
1307      * @throws IllegalArgumentException if pad width is too small
1308      */
1309     public DateTimeFormatterBuilder padNext(int padWidth) {
1310         return padNext(padWidth, ' ');
1311     }
1312 
1313     /**
1314      * Causes the next added printer/parser to pad to a fixed width.
1315      * <p>
1316      * This padding is intended for padding other than zero-padding.
1317      * Zero-padding should be achieved using the appendValue methods.
1318      * <p>
1319      * An exception will be thrown during printing if the pad width
1320      * is exceeded.







1321      *
1322      * @param padWidth  the pad width, 1 or greater
1323      * @param padChar  the pad character
1324      * @return this, for chaining, not null
1325      * @throws IllegalArgumentException if pad width is too small
1326      */
1327     public DateTimeFormatterBuilder padNext(int padWidth, char padChar) {
1328         if (padWidth < 1) {
1329             throw new IllegalArgumentException("The pad width must be at least one but was " + padWidth);
1330         }
1331         active.padNextWidth = padWidth;
1332         active.padNextChar = padChar;
1333         active.valueParserIndex = -1;
1334         return this;
1335     }
1336 
1337     //-----------------------------------------------------------------------
1338     /**
1339      * Mark the start of an optional section.
1340      * <p>
1341      * The output of printing can include optional sections, which may be nested.
1342      * An optional section is started by calling this method and ended by calling
1343      * {@link #optionalEnd()} or by ending the build process.
1344      * <p>
1345      * All elements in the optional section are treated as optional.
1346      * During printing, the section is only output if data is available in the
1347      * {@code TemporalAccessor} for all the elements in the section.
1348      * During parsing, the whole section may be missing from the parsed string.
1349      * <p>
1350      * For example, consider a builder setup as
1351      * {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2)}.
1352      * The optional section ends automatically at the end of the builder.
1353      * During printing, the minute will only be output if its value can be obtained from the date-time.
1354      * During parsing, the input will be successfully parsed whether the minute is present or not.
1355      *
1356      * @return this, for chaining, not null
1357      */
1358     public DateTimeFormatterBuilder optionalStart() {
1359         active.valueParserIndex = -1;
1360         active = new DateTimeFormatterBuilder(active, true);
1361         return this;
1362     }
1363 
1364     /**
1365      * Ends an optional section.
1366      * <p>
1367      * The output of printing can include optional sections, which may be nested.
1368      * An optional section is started by calling {@link #optionalStart()} and ended
1369      * using this method (or at the end of the builder).
1370      * <p>
1371      * Calling this method without having previously called {@code optionalStart}
1372      * will throw an exception.
1373      * Calling this method immediately after calling {@code optionalStart} has no effect
1374      * on the formatter other than ending the (empty) optional section.
1375      * <p>
1376      * All elements in the optional section are treated as optional.
1377      * During printing, the section is only output if data is available in the
1378      * {@code TemporalAccessor} for all the elements in the section.
1379      * During parsing, the whole section may be missing from the parsed string.
1380      * <p>
1381      * For example, consider a builder setup as
1382      * {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2).optionalEnd()}.
1383      * During printing, the minute will only be output if its value can be obtained from the date-time.
1384      * During parsing, the input will be successfully parsed whether the minute is present or not.
1385      *
1386      * @return this, for chaining, not null
1387      * @throws IllegalStateException if there was no previous call to {@code optionalStart}
1388      */
1389     public DateTimeFormatterBuilder optionalEnd() {
1390         if (active.parent == null) {
1391             throw new IllegalStateException("Cannot call optionalEnd() as there was no previous call to optionalStart()");
1392         }
1393         if (active.printerParsers.size() > 0) {
1394             CompositePrinterParser cpp = new CompositePrinterParser(active.printerParsers, active.optional);
1395             active = active.parent;
1396             appendInternal(cpp);
1397         } else {
1398             active = active.parent;
1399         }
1400         return this;
1401     }
1402 
1403     //-----------------------------------------------------------------------


1449      * Calling this method will end any open optional sections by repeatedly
1450      * calling {@link #optionalEnd()} before creating the formatter.
1451      * <p>
1452      * This builder can still be used after creating the formatter if desired,
1453      * although the state may have been changed by calls to {@code optionalEnd}.
1454      *
1455      * @param locale  the locale to use for formatting, not null
1456      * @return the created formatter, not null
1457      */
1458     public DateTimeFormatter toFormatter(Locale locale) {
1459         Objects.requireNonNull(locale, "locale");
1460         while (active.parent != null) {
1461             optionalEnd();
1462         }
1463         CompositePrinterParser pp = new CompositePrinterParser(printerParsers, false);
1464         return new DateTimeFormatter(pp, locale, DateTimeFormatSymbols.STANDARD, null, null);
1465     }
1466 
1467     //-----------------------------------------------------------------------
1468     /**
1469      * Strategy for printing/parsing date-time information.
1470      * <p>
1471      * The printer may print any part, or the whole, of the input date-time object.
1472      * Typically, a complete print is constructed from a number of smaller
1473      * units, each outputting a single field.
1474      * <p>
1475      * The parser may parse any piece of text from the input, storing the result
1476      * in the context. Typically, each individual parser will just parse one
1477      * field, such as the day-of-month, storing the value in the context.
1478      * Once the parse is complete, the caller will then convert the context
1479      * to a {@link DateTimeBuilder} to merge the parsed values to create the
1480      * desired object, such as a {@code LocalDate}.
1481      * <p>
1482      * The parse position will be updated during the parse. Parsing will start at
1483      * the specified index and the return value specifies the new parse position
1484      * for the next parser. If an error occurs, the returned index will be negative
1485      * and will have the error position encoded using the complement operator.
1486      *
1487      * <h3>Specification for implementors</h3>
1488      * This interface must be implemented with care to ensure other classes operate correctly.
1489      * All implementations that can be instantiated must be final, immutable and thread-safe.
1490      * <p>
1491      * The context is not a thread-safe object and a new instance will be created
1492      * for each print that occurs. The context must not be stored in an instance
1493      * variable or shared with any other threads.
1494      */
1495     interface DateTimePrinterParser {
1496 
1497         /**
1498          * Prints the date-time object to the buffer.
1499          * <p>
1500          * The context holds information to use during the print.
1501          * It also contains the date-time information to be printed.
1502          * <p>
1503          * The buffer must not be mutated beyond the content controlled by the implementation.
1504          *
1505          * @param context  the context to print using, not null
1506          * @param buf  the buffer to append to, not null
1507          * @return false if unable to query the value from the date-time, true otherwise
1508          * @throws DateTimeException if the date-time cannot be printed successfully
1509          */
1510         boolean print(DateTimePrintContext context, StringBuilder buf);
1511 
1512         /**
1513          * Parses text into date-time information.
1514          * <p>
1515          * The context holds information to use during the parse.
1516          * It is also used to store the parsed date-time information.
1517          *
1518          * @param context  the context to use and parse into, not null
1519          * @param text  the input text to parse, not null
1520          * @param position  the position to start parsing at, from 0 to the text length
1521          * @return the new parse position, where negative means an error with the
1522          *  error position encoded using the complement ~ operator
1523          * @throws NullPointerException if the context or text is null
1524          * @throws IndexOutOfBoundsException if the position is invalid
1525          */
1526         int parse(DateTimeParseContext context, CharSequence text, int position);
1527     }
1528 
1529     //-----------------------------------------------------------------------
1530     /**


1540 
1541         CompositePrinterParser(DateTimePrinterParser[] printerParsers, boolean optional) {
1542             this.printerParsers = printerParsers;
1543             this.optional = optional;
1544         }
1545 
1546         /**
1547          * Returns a copy of this printer-parser with the optional flag changed.
1548          *
1549          * @param optional  the optional flag to set in the copy
1550          * @return the new printer-parser, not null
1551          */
1552         public CompositePrinterParser withOptional(boolean optional) {
1553             if (optional == this.optional) {
1554                 return this;
1555             }
1556             return new CompositePrinterParser(printerParsers, optional);
1557         }
1558 
1559         @Override
1560         public boolean print(DateTimePrintContext context, StringBuilder buf) {
1561             int length = buf.length();
1562             if (optional) {
1563                 context.startOptional();
1564             }
1565             try {
1566                 for (DateTimePrinterParser pp : printerParsers) {
1567                     if (pp.print(context, buf) == false) {
1568                         buf.setLength(length);  // reset buffer
1569                         return true;
1570                     }
1571                 }
1572             } finally {
1573                 if (optional) {
1574                     context.endOptional();
1575                 }
1576             }
1577             return true;
1578         }
1579 
1580         @Override
1581         public int parse(DateTimeParseContext context, CharSequence text, int position) {
1582             if (optional) {
1583                 context.startOptional();
1584                 int pos = position;
1585                 for (DateTimePrinterParser pp : printerParsers) {
1586                     pos = pp.parse(context, text, pos);
1587                     if (pos < 0) {


1623     static final class PadPrinterParserDecorator implements DateTimePrinterParser {
1624         private final DateTimePrinterParser printerParser;
1625         private final int padWidth;
1626         private final char padChar;
1627 
1628         /**
1629          * Constructor.
1630          *
1631          * @param printerParser  the printer, not null
1632          * @param padWidth  the width to pad to, 1 or greater
1633          * @param padChar  the pad character
1634          */
1635         PadPrinterParserDecorator(DateTimePrinterParser printerParser, int padWidth, char padChar) {
1636             // input checked by DateTimeFormatterBuilder
1637             this.printerParser = printerParser;
1638             this.padWidth = padWidth;
1639             this.padChar = padChar;
1640         }
1641 
1642         @Override
1643         public boolean print(DateTimePrintContext context, StringBuilder buf) {
1644             int preLen = buf.length();
1645             if (printerParser.print(context, buf) == false) {
1646                 return false;
1647             }
1648             int len = buf.length() - preLen;
1649             if (len > padWidth) {
1650                 throw new DateTimePrintException(
1651                     "Cannot print as output of " + len + " characters exceeds pad width of " + padWidth);
1652             }
1653             for (int i = 0; i < padWidth - len; i++) {
1654                 buf.insert(preLen, padChar);
1655             }
1656             return true;
1657         }
1658 
1659         @Override
1660         public int parse(DateTimeParseContext context, CharSequence text, int position) {



1661             if (position > text.length()) {
1662                 throw new IndexOutOfBoundsException();
1663             }



1664             int endPos = position + padWidth;
1665             if (endPos > text.length()) {

1666                 return ~position;  // not enough characters in the string to meet the parse width
1667             }


1668             int pos = position;
1669             while (pos < endPos && text.charAt(pos) == padChar) {
1670                 pos++;
1671             }
1672             text = text.subSequence(0, endPos);
1673             int firstError = 0;
1674             while (pos >= position) {
1675                 int resultPos = printerParser.parse(context, text, pos);
1676                 if (resultPos < 0) {
1677                     // parse of decorated field had an error
1678                     if (firstError == 0) {
1679                         firstError = resultPos;
1680                     }
1681                     // loop around in case the decorated parser can handle the padChar at the start
1682                     pos--;
1683                     continue;
1684                 }
1685                 if (resultPos != endPos) {
1686                     return ~position;  // parse of decorated field didn't parse to the end
1687                 }
1688                 return resultPos;
1689             }
1690             // loop runs at least once, so firstError must be set by the time we get here
1691             return firstError;  // return error from first parse of decorated field
1692         }
1693 
1694         @Override
1695         public String toString() {
1696             return "Pad(" + printerParser + "," + padWidth + (padChar == ' ' ? ")" : ",'" + padChar + "')");
1697         }
1698     }
1699 
1700     //-----------------------------------------------------------------------
1701     /**
1702      * Enumeration to apply simple parse settings.
1703      */
1704     static enum SettingsParser implements DateTimePrinterParser {
1705         SENSITIVE,
1706         INSENSITIVE,
1707         STRICT,
1708         LENIENT;
1709 
1710         @Override
1711         public boolean print(DateTimePrintContext context, StringBuilder buf) {
1712             return true;  // nothing to do here
1713         }
1714 
1715         @Override
1716         public int parse(DateTimeParseContext context, CharSequence text, int position) {
1717             // using ordinals to avoid javac synthetic inner class
1718             switch (ordinal()) {
1719                 case 0: context.setCaseSensitive(true); break;
1720                 case 1: context.setCaseSensitive(false); break;
1721                 case 2: context.setStrict(true); break;
1722                 case 3: context.setStrict(false); break;
1723             }
1724             return position;
1725         }
1726 
1727         @Override
1728         public String toString() {
1729             // using ordinals to avoid javac synthetic inner class
1730             switch (ordinal()) {
1731                 case 0: return "ParseCaseSensitive(true)";
1732                 case 1: return "ParseCaseSensitive(false)";
1733                 case 2: return "ParseStrict(true)";
1734                 case 3: return "ParseStrict(false)";
1735             }
1736             throw new IllegalStateException("Unreachable");
1737         }
1738     }
1739 
1740     //-----------------------------------------------------------------------
1741     /**
1742      * Prints or parses a character literal.
1743      */
1744     static final class CharLiteralPrinterParser implements DateTimePrinterParser {
1745         private final char literal;
1746 
1747         CharLiteralPrinterParser(char literal) {
1748             this.literal = literal;
1749         }
1750 
1751         @Override
1752         public boolean print(DateTimePrintContext context, StringBuilder buf) {
1753             buf.append(literal);
1754             return true;
1755         }
1756 
1757         @Override
1758         public int parse(DateTimeParseContext context, CharSequence text, int position) {
1759             int length = text.length();
1760             if (position == length) {
1761                 return ~position;
1762             }
1763             char ch = text.charAt(position);
1764             if (ch != literal) {
1765                 if (context.isCaseSensitive() ||
1766                         (Character.toUpperCase(ch) != Character.toUpperCase(literal) &&
1767                          Character.toLowerCase(ch) != Character.toLowerCase(literal))) {
1768                     return ~position;
1769                 }
1770             }
1771             return position + 1;
1772         }


1775         public String toString() {
1776             if (literal == '\'') {
1777                 return "''";
1778             }
1779             return "'" + literal + "'";
1780         }
1781     }
1782 
1783     //-----------------------------------------------------------------------
1784     /**
1785      * Prints or parses a string literal.
1786      */
1787     static final class StringLiteralPrinterParser implements DateTimePrinterParser {
1788         private final String literal;
1789 
1790         StringLiteralPrinterParser(String literal) {
1791             this.literal = literal;  // validated by caller
1792         }
1793 
1794         @Override
1795         public boolean print(DateTimePrintContext context, StringBuilder buf) {
1796             buf.append(literal);
1797             return true;
1798         }
1799 
1800         @Override
1801         public int parse(DateTimeParseContext context, CharSequence text, int position) {
1802             int length = text.length();
1803             if (position > length || position < 0) {
1804                 throw new IndexOutOfBoundsException();
1805             }
1806             if (context.subSequenceEquals(text, position, literal, 0, literal.length()) == false) {
1807                 return ~position;
1808             }
1809             return position + literal.length();
1810         }
1811 
1812         @Override
1813         public String toString() {
1814             String converted = literal.replace("'", "''");
1815             return "'" + converted + "'";


1830             10,
1831             100,
1832             1000,
1833             10000,
1834             100000,
1835             1000000,
1836             10000000,
1837             100000000,
1838             1000000000,
1839         };
1840 
1841         final TemporalField field;
1842         final int minWidth;
1843         private final int maxWidth;
1844         private final SignStyle signStyle;
1845         private final int subsequentWidth;
1846 
1847         /**
1848          * Constructor.
1849          *
1850          * @param field  the field to print, not null
1851          * @param minWidth  the minimum field width, from 1 to 19
1852          * @param maxWidth  the maximum field width, from minWidth to 19
1853          * @param signStyle  the positive/negative sign style, not null
1854          */
1855         NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) {
1856             // validated by caller
1857             this.field = field;
1858             this.minWidth = minWidth;
1859             this.maxWidth = maxWidth;
1860             this.signStyle = signStyle;
1861             this.subsequentWidth = 0;
1862         }
1863 
1864         /**
1865          * Constructor.
1866          *
1867          * @param field  the field to print, not null
1868          * @param minWidth  the minimum field width, from 1 to 19
1869          * @param maxWidth  the maximum field width, from minWidth to 19
1870          * @param signStyle  the positive/negative sign style, not null
1871          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater,
1872          *  -1 if fixed width due to active adjacent parsing
1873          */
1874         private NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle, int subsequentWidth) {
1875             // validated by caller
1876             this.field = field;
1877             this.minWidth = minWidth;
1878             this.maxWidth = maxWidth;
1879             this.signStyle = signStyle;
1880             this.subsequentWidth = subsequentWidth;
1881         }
1882 
1883         /**
1884          * Returns a new instance with fixed width flag set.
1885          *
1886          * @return a new updated printer-parser, not null
1887          */
1888         NumberPrinterParser withFixedWidth() {
1889             return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, -1);
1890         }
1891 
1892         /**
1893          * Returns a new instance with an updated subsequent width.
1894          *
1895          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater
1896          * @return a new updated printer-parser, not null
1897          */
1898         NumberPrinterParser withSubsequentWidth(int subsequentWidth) {
1899             return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, this.subsequentWidth + subsequentWidth);
1900         }
1901 
1902         @Override
1903         public boolean print(DateTimePrintContext context, StringBuilder buf) {
1904             Long valueLong = context.getValue(field);






1905             if (valueLong == null) {
1906                 return false;
1907             }
1908             long value = getValue(valueLong);
1909             DateTimeFormatSymbols symbols = context.getSymbols();
1910             String str = (value == Long.MIN_VALUE ? "9223372036854775808" : Long.toString(Math.abs(value)));
1911             if (str.length() > maxWidth) {
1912                 throw new DateTimePrintException("Field " + field.getName() +
1913                     " cannot be printed as the value " + value +
1914                     " exceeds the maximum print width of " + maxWidth);
1915             }
1916             str = symbols.convertNumberToI18N(str);
1917 
1918             if (value >= 0) {
1919                 switch (signStyle) {
1920                     case EXCEEDS_PAD:
1921                         if (minWidth < 19 && value >= EXCEED_POINTS[minWidth]) {
1922                             buf.append(symbols.getPositiveSign());
1923                         }
1924                         break;
1925                     case ALWAYS:
1926                         buf.append(symbols.getPositiveSign());
1927                         break;
1928                 }
1929             } else {
1930                 switch (signStyle) {
1931                     case NORMAL:
1932                     case EXCEEDS_PAD:
1933                     case ALWAYS:
1934                         buf.append(symbols.getNegativeSign());
1935                         break;
1936                     case NOT_NEGATIVE:
1937                         throw new DateTimePrintException("Field " + field.getName() +
1938                             " cannot be printed as the value " + value +
1939                             " cannot be negative according to the SignStyle");
1940                 }
1941             }
1942             for (int i = 0; i < minWidth - str.length(); i++) {
1943                 buf.append(symbols.getZeroDigit());
1944             }
1945             buf.append(str);
1946             return true;
1947         }
1948 
1949         /**
1950          * Gets the value to output.
1951          *
1952          * @param value  the base value of the field, not null
1953          * @return the value
1954          */
1955         long getValue(long value) {
1956             return value;
1957         }


2040                     total = -total;
2041                 }
2042             } else if (signStyle == SignStyle.EXCEEDS_PAD && context.isStrict()) {
2043                 int parseLen = pos - position;
2044                 if (positive) {
2045                     if (parseLen <= minWidth) {
2046                         return ~(position - 1);  // '+' only parsed if minWidth exceeded
2047                     }
2048                 } else {
2049                     if (parseLen > minWidth) {
2050                         return ~position;  // '+' must be parsed if minWidth exceeded
2051                     }
2052                 }
2053             }
2054             if (totalBig != null) {
2055                 if (totalBig.bitLength() > 63) {
2056                     // overflow, parse 1 less digit
2057                     totalBig = totalBig.divide(BigInteger.TEN);
2058                     pos--;
2059                 }
2060                 setValue(context, totalBig.longValue());
2061             } else {
2062                 setValue(context, total);
2063             }
2064             return pos;
2065         }
2066 
2067         /**
2068          * Stores the value.
2069          *
2070          * @param context  the context to store into, not null
2071          * @param value  the value
2072          */
2073         void setValue(DateTimeParseContext context, long value) {
2074             context.setParsedField(field, value);










2075         }
2076 
2077         @Override
2078         public String toString() {
2079             if (minWidth == 1 && maxWidth == 19 && signStyle == SignStyle.NORMAL) {
2080                 return "Value(" + field.getName() + ")";
2081             }
2082             if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) {
2083                 return "Value(" + field.getName() + "," + minWidth + ")";
2084             }
2085             return "Value(" + field.getName() + "," + minWidth + "," + maxWidth + "," + signStyle + ")";
2086         }
2087     }
2088 
2089     //-----------------------------------------------------------------------
2090     /**
2091      * Prints and parses a reduced numeric date-time field.
2092      */
2093     static final class ReducedPrinterParser extends NumberPrinterParser {
2094         private final int baseValue;
2095         private final int range;
2096 
2097         /**
2098          * Constructor.
2099          *
2100          * @param field  the field to print, validated not null
2101          * @param width  the field width, from 1 to 18
2102          * @param baseValue  the base value
2103          */
2104         ReducedPrinterParser(TemporalField field, int width, int baseValue) {
2105             super(field, width, width, SignStyle.NOT_NEGATIVE);
2106             if (width < 1 || width > 18) {
2107                 throw new IllegalArgumentException("The width must be from 1 to 18 inclusive but was " + width);
2108             }
2109             if (field.range().isValidValue(baseValue) == false) {
2110                 throw new IllegalArgumentException("The base value must be within the range of the field");
2111             }
2112             this.baseValue = baseValue;
2113             this.range = EXCEED_POINTS[width];
2114             if ((((long) baseValue) + range) > Integer.MAX_VALUE) {
2115                 throw new DateTimeException("Unable to add printer-parser as the range exceeds the capacity of an int");
2116             }
2117         }
2118 
2119         @Override
2120         long getValue(long value) {
2121             return Math.abs(value % range);
2122         }
2123 
2124         @Override
2125         void setValue(DateTimeParseContext context, long value) {
2126             int lastPart = baseValue % range;
2127             if (baseValue > 0) {
2128                 value = baseValue - lastPart + value;
2129             } else {
2130                 value = baseValue - lastPart - value;
2131             }
2132             if (value < baseValue) {
2133                 value += range;
2134             }
2135             context.setParsedField(field, value);
2136         }
2137 
2138         @Override
2139         NumberPrinterParser withFixedWidth() {
2140             return this;
2141         }
2142 
2143         @Override
2144         boolean isFixedWidth() {
2145             return true;
2146         }
2147 
2148         @Override
2149         public String toString() {
2150             return "ReducedValue(" + field.getName() + "," + minWidth + "," + baseValue + ")";
2151         }
2152     }
2153 
2154     //-----------------------------------------------------------------------
2155     /**


2174             if (field.range().isFixed() == false) {
2175                 throw new IllegalArgumentException("Field must have a fixed set of values: " + field.getName());
2176             }
2177             if (minWidth < 0 || minWidth > 9) {
2178                 throw new IllegalArgumentException("Minimum width must be from 0 to 9 inclusive but was " + minWidth);
2179             }
2180             if (maxWidth < 1 || maxWidth > 9) {
2181                 throw new IllegalArgumentException("Maximum width must be from 1 to 9 inclusive but was " + maxWidth);
2182             }
2183             if (maxWidth < minWidth) {
2184                 throw new IllegalArgumentException("Maximum width must exceed or equal the minimum width but " +
2185                         maxWidth + " < " + minWidth);
2186             }
2187             this.field = field;
2188             this.minWidth = minWidth;
2189             this.maxWidth = maxWidth;
2190             this.decimalPoint = decimalPoint;
2191         }
2192 
2193         @Override
2194         public boolean print(DateTimePrintContext context, StringBuilder buf) {
2195             Long value = context.getValue(field);
2196             if (value == null) {
2197                 return false;
2198             }
2199             DateTimeFormatSymbols symbols = context.getSymbols();
2200             BigDecimal fraction = convertToFraction(value);
2201             if (fraction.scale() == 0) {  // scale is zero if value is zero
2202                 if (minWidth > 0) {
2203                     if (decimalPoint) {
2204                         buf.append(symbols.getDecimalSeparator());
2205                     }
2206                     for (int i = 0; i < minWidth; i++) {
2207                         buf.append(symbols.getZeroDigit());
2208                     }
2209                 }
2210             } else {
2211                 int outputScale = Math.min(Math.max(fraction.scale(), minWidth), maxWidth);
2212                 fraction = fraction.setScale(outputScale, RoundingMode.FLOOR);
2213                 String str = fraction.toPlainString().substring(2);
2214                 str = symbols.convertNumberToI18N(str);


2240             if (minEndPos > length) {
2241                 return ~position;  // need at least min width digits
2242             }
2243             int maxEndPos = Math.min(position + effectiveMax, length);
2244             int total = 0;  // can use int because we are only parsing up to 9 digits
2245             int pos = position;
2246             while (pos < maxEndPos) {
2247                 char ch = text.charAt(pos++);
2248                 int digit = context.getSymbols().convertToDigit(ch);
2249                 if (digit < 0) {
2250                     if (pos < minEndPos) {
2251                         return ~position;  // need at least min width digits
2252                     }
2253                     pos--;
2254                     break;
2255                 }
2256                 total = total * 10 + digit;
2257             }
2258             BigDecimal fraction = new BigDecimal(total).movePointLeft(pos - position);
2259             long value = convertFromFraction(fraction);
2260             context.setParsedField(field, value);
2261             return pos;
2262         }
2263 
2264         /**
2265          * Converts a value for this field to a fraction between 0 and 1.
2266          * <p>
2267          * The fractional value is between 0 (inclusive) and 1 (exclusive).
2268          * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
2269          * The fraction is obtained by calculation from the field range using 9 decimal
2270          * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
2271          * The calculation is inaccurate if the values do not run continuously from smallest to largest.
2272          * <p>
2273          * For example, the second-of-minute value of 15 would be returned as 0.25,
2274          * assuming the standard definition of 60 seconds in a minute.
2275          *
2276          * @param value  the value to convert, must be valid for this rule
2277          * @return the value as a fraction within the range, from 0 to 1, not null
2278          * @throws DateTimeException if the value cannot be converted to a fraction
2279          */
2280         private BigDecimal convertToFraction(long value) {
2281             ValueRange range = field.range();


2331          * The cached number printer parser.
2332          * Immutable and volatile, so no synchronization needed.
2333          */
2334         private volatile NumberPrinterParser numberPrinterParser;
2335 
2336         /**
2337          * Constructor.
2338          *
2339          * @param field  the field to output, not null
2340          * @param textStyle  the text style, not null
2341          * @param provider  the text provider, not null
2342          */
2343         TextPrinterParser(TemporalField field, TextStyle textStyle, DateTimeTextProvider provider) {
2344             // validated by caller
2345             this.field = field;
2346             this.textStyle = textStyle;
2347             this.provider = provider;
2348         }
2349 
2350         @Override
2351         public boolean print(DateTimePrintContext context, StringBuilder buf) {
2352             Long value = context.getValue(field);
2353             if (value == null) {
2354                 return false;
2355             }
2356             String text = null;
2357             if (field == ChronoField.ERA) {
2358                 Chrono chrono = context.getTemporal().query(Queries.chrono());
2359                 if (chrono == null) {
2360                     chrono = ISOChrono.INSTANCE;
2361                 }
2362                 text = provider.getEraText(chrono, value, textStyle, context.getLocale());
2363             } else {
2364                 text = provider.getText(field, value, textStyle, context.getLocale());


2365             }
2366             if (text == null) {
2367                 return numberPrinterParser().print(context, buf);
2368             }
2369             buf.append(text);
2370             return true;
2371         }
2372 
2373         @Override
2374         public int parse(DateTimeParseContext context, CharSequence parseText, int position) {
2375             int length = parseText.length();
2376             if (position < 0 || position > length) {
2377                 throw new IndexOutOfBoundsException();
2378             }
2379             TextStyle style = (context.isStrict() ? textStyle : null);
2380             Iterator<Entry<String, Long>> it = provider.getTextIterator(field, style, context.getLocale());






2381             if (it != null) {
2382                 while (it.hasNext()) {
2383                     Entry<String, Long> entry = it.next();
2384                     String itText = entry.getKey();
2385                     if (context.subSequenceEquals(itText, 0, parseText, position, itText.length())) {
2386                         context.setParsedField(field, entry.getValue());
2387                         return position + itText.length();
2388                     }
2389                 }
2390                 if (context.isStrict()) {
2391                     return ~position;
2392                 }
2393             }
2394             return numberPrinterParser().parse(context, parseText, position);
2395         }
2396 
2397         /**
2398          * Create and cache a number printer parser.
2399          * @return the number printer parser for this field, not null
2400          */
2401         private NumberPrinterParser numberPrinterParser() {
2402             if (numberPrinterParser == null) {
2403                 numberPrinterParser = new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL);
2404             }
2405             return numberPrinterParser;
2406         }
2407 


2409         public String toString() {
2410             if (textStyle == TextStyle.FULL) {
2411                 return "Text(" + field.getName() + ")";
2412             }
2413             return "Text(" + field.getName() + "," + textStyle + ")";
2414         }
2415     }
2416 
2417     //-----------------------------------------------------------------------
2418     /**
2419      * Prints or parses an ISO-8601 instant.
2420      */
2421     static final class InstantPrinterParser implements DateTimePrinterParser {
2422         // days in a 400 year cycle = 146097
2423         // days in a 10,000 year cycle = 146097 * 25
2424         // seconds per day = 86400
2425         private static final long SECONDS_PER_10000_YEARS = 146097L * 25L * 86400L;
2426         private static final long SECONDS_0000_TO_1970 = ((146097L * 5L) - (30L * 365L + 7L)) * 86400L;
2427         private static final CompositePrinterParser PARSER = new DateTimeFormatterBuilder()
2428                     .parseCaseInsensitive()
2429                     .append(DateTimeFormatters.isoLocalDate()).appendLiteral('T')
2430                     .append(DateTimeFormatters.isoLocalTime()).appendLiteral('Z')
2431                     .toFormatter().toPrinterParser(false);
2432 
2433         InstantPrinterParser() {
2434         }
2435 
2436         @Override
2437         public boolean print(DateTimePrintContext context, StringBuilder buf) {
2438             // use INSTANT_SECONDS, thus this code is not bound by Instant.MAX
2439             Long inSecs = context.getValue(INSTANT_SECONDS);
2440             Long inNanos = context.getValue(NANO_OF_SECOND);
2441             if (inSecs == null || inNanos == null) {
2442                 return false;
2443             }
2444             long inSec = inSecs;
2445             int inNano = NANO_OF_SECOND.checkValidIntValue(inNanos);
2446             if (inSec >= -SECONDS_0000_TO_1970) {
2447                 // current era
2448                 long zeroSecs = inSec - SECONDS_PER_10000_YEARS + SECONDS_0000_TO_1970;
2449                 long hi = Math.floorDiv(zeroSecs, SECONDS_PER_10000_YEARS) + 1;
2450                 long lo = Math.floorMod(zeroSecs, SECONDS_PER_10000_YEARS);
2451                 LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, inNano, ZoneOffset.UTC);
2452                 if (hi > 0) {
2453                     buf.append('+').append(hi);
2454                 }
2455                 buf.append(ldt).append('Z');
2456             } else {
2457                 // before current era


2485             // parser restricts most fields to 2 digits, so definitely int
2486             // correctly parsed nano is also guaranteed to be valid
2487             long yearParsed = newContext.getParsed(YEAR);
2488             int month = newContext.getParsed(MONTH_OF_YEAR).intValue();
2489             int day = newContext.getParsed(DAY_OF_MONTH).intValue();
2490             int hour = newContext.getParsed(HOUR_OF_DAY).intValue();
2491             int min = newContext.getParsed(MINUTE_OF_HOUR).intValue();
2492             Long secVal = newContext.getParsed(SECOND_OF_MINUTE);
2493             Long nanoVal = newContext.getParsed(NANO_OF_SECOND);
2494             int sec = (secVal != null ? secVal.intValue() : 0);
2495             int nano = (nanoVal != null ? nanoVal.intValue() : 0);
2496             int year = (int) yearParsed % 10_000;
2497             long instantSecs;
2498             try {
2499                 LocalDateTime ldt = LocalDateTime.of(year, month, day, hour, min, sec, 0);
2500                 instantSecs = ldt.toEpochSecond(ZoneOffset.UTC);
2501                 instantSecs += Math.multiplyExact(yearParsed / 10_000L, SECONDS_PER_10000_YEARS);
2502             } catch (RuntimeException ex) {
2503                 return ~position;
2504             }
2505             context.setParsedField(INSTANT_SECONDS, instantSecs);
2506             context.setParsedField(NANO_OF_SECOND, nano);
2507             return text.length();
2508         }
2509 
2510         @Override
2511         public String toString() {
2512             return "Instant()";
2513         }
2514     }
2515 
2516     //-----------------------------------------------------------------------
2517     /**
2518      * Prints or parses an offset ID.
2519      */
2520     static final class OffsetIdPrinterParser implements DateTimePrinterParser {
2521         static final String[] PATTERNS = new String[] {
2522             "+HH", "+HHMM", "+HH:MM", "+HHMMss", "+HH:MM:ss", "+HHMMSS", "+HH:MM:SS",
2523         };  // order used in pattern builder
2524         static final OffsetIdPrinterParser INSTANCE_ID = new OffsetIdPrinterParser("Z", "+HH:MM:ss");

2525 
2526         private final String noOffsetText;
2527         private final int type;
2528 
2529         /**
2530          * Constructor.
2531          *
2532          * @param noOffsetText  the text to use for UTC, not null
2533          * @param pattern  the pattern

2534          */
2535         OffsetIdPrinterParser(String noOffsetText, String pattern) {
2536             Objects.requireNonNull(noOffsetText, "noOffsetText");
2537             Objects.requireNonNull(pattern, "pattern");
2538             this.noOffsetText = noOffsetText;
2539             this.type = checkPattern(pattern);

2540         }
2541 
2542         private int checkPattern(String pattern) {
2543             for (int i = 0; i < PATTERNS.length; i++) {
2544                 if (PATTERNS[i].equals(pattern)) {
2545                     return i;
2546                 }
2547             }
2548             throw new IllegalArgumentException("Invalid zone offset pattern: " + pattern);
2549         }
2550 
2551         @Override
2552         public boolean print(DateTimePrintContext context, StringBuilder buf) {
2553             Long offsetSecs = context.getValue(OFFSET_SECONDS);
2554             if (offsetSecs == null) {
2555                 return false;
2556             }
2557             int totalSecs = Math.toIntExact(offsetSecs);
2558             if (totalSecs == 0) {
2559                 buf.append(noOffsetText);
2560             } else {
2561                 int absHours = Math.abs((totalSecs / 3600) % 100);  // anything larger than 99 silently dropped
2562                 int absMinutes = Math.abs((totalSecs / 60) % 60);
2563                 int absSeconds = Math.abs(totalSecs % 60);


2564                 buf.append(totalSecs < 0 ? "-" : "+")
2565                     .append((char) (absHours / 10 + '0')).append((char) (absHours % 10 + '0'));
2566                 if (type >= 1) {
2567                     buf.append((type % 2) == 0 ? ":" : "")
2568                         .append((char) (absMinutes / 10 + '0')).append((char) (absMinutes % 10 + '0'));
2569                     if (type >= 5 || (type >= 3 && absSeconds > 0)) {

2570                         buf.append((type % 2) == 0 ? ":" : "")
2571                             .append((char) (absSeconds / 10 + '0')).append((char) (absSeconds % 10 + '0'));


2572                     }



2573                 }
2574             }
2575             return true;
2576         }
2577 
2578         @Override
2579         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2580             int length = text.length();
2581             int noOffsetLen = noOffsetText.length();
2582             if (noOffsetLen == 0) {
2583                 if (position == length) {
2584                     context.setParsedField(OFFSET_SECONDS, 0);
2585                     return position;
2586                 }
2587             } else {
2588                 if (position == length) {
2589                     return ~position;
2590                 }
2591                 if (context.subSequenceEquals(text, position, noOffsetText, 0, noOffsetLen)) {
2592                     context.setParsedField(OFFSET_SECONDS, 0);
2593                     return position + noOffsetLen;
2594                 }
2595             }
2596 
2597             // parse normal plus/minus offset
2598             char sign = text.charAt(position);  // IOOBE if invalid position
2599             if (sign == '+' || sign == '-') {
2600                 // starts
2601                 int negative = (sign == '-' ? -1 : 1);
2602                 int[] array = new int[4];
2603                 array[0] = position + 1;
2604                 if (parseNumber(array, 1, text, true) ||
2605                         parseNumber(array, 2, text, type > 0) ||
2606                         parseNumber(array, 3, text, false)) {
2607                     return ~position;
2608                 }
2609                 long offsetSecs = negative * (array[1] * 3600L + array[2] * 60L + array[3]);
2610                 context.setParsedField(OFFSET_SECONDS, offsetSecs);
2611                 return array[0];
2612             } else {
2613                 // handle special case of empty no offset text
2614                 if (noOffsetLen == 0) {
2615                     context.setParsedField(OFFSET_SECONDS, 0);
2616                     return position + noOffsetLen;
2617                 }
2618                 return ~position;
2619             }
2620         }
2621 
2622         /**
2623          * Parse a two digit zero-prefixed number.
2624          *
2625          * @param array  the array of parsed data, 0=pos,1=hours,2=mins,3=secs, not null
2626          * @param arrayIndex  the index to parse the value into
2627          * @param parseText  the offset ID, not null
2628          * @param required  whether this number is required
2629          * @return true if an error occurred
2630          */
2631         private boolean parseNumber(int[] array, int arrayIndex, CharSequence parseText, boolean required) {
2632             if ((type + 3) / 2 < arrayIndex) {
2633                 return false;  // ignore seconds/minutes
2634             }
2635             int pos = array[0];
2636             if ((type % 2) == 0 && arrayIndex > 1) {
2637                 if (pos + 1 > parseText.length() || parseText.charAt(pos) != ':') {
2638                     return required;
2639                 }
2640                 pos++;


2642             if (pos + 2 > parseText.length()) {
2643                 return required;
2644             }
2645             char ch1 = parseText.charAt(pos++);
2646             char ch2 = parseText.charAt(pos++);
2647             if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') {
2648                 return required;
2649             }
2650             int value = (ch1 - 48) * 10 + (ch2 - 48);
2651             if (value < 0 || value > 59) {
2652                 return required;
2653             }
2654             array[arrayIndex] = value;
2655             array[0] = pos;
2656             return false;
2657         }
2658 
2659         @Override
2660         public String toString() {
2661             String converted = noOffsetText.replace("'", "''");
2662             return "Offset('" + converted + "'," + PATTERNS[type] + ")";
2663         }
2664     }
2665 
2666     //-----------------------------------------------------------------------
2667     /**
2668      * Prints or parses a zone ID.
2669      */
2670     static final class ZoneTextPrinterParser implements DateTimePrinterParser {
2671 
2672         /** The text style to output. */
2673         private final TextStyle textStyle;
2674 
2675         ZoneTextPrinterParser(TextStyle textStyle) {




2676             this.textStyle = Objects.requireNonNull(textStyle, "textStyle");






2677         }
2678 
2679         private static final int STD = 0;
2680         private static final int DST = 1;
2681         private static final int GENERIC = 2;
2682 
2683         private static final Map<String, SoftReference<Map<Locale, String[]>>> cache =
2684             new ConcurrentHashMap<>();
2685 
2686         private static String getDisplayName(String id, int type, TextStyle style, Locale locale) {
2687             if (style == TextStyle.NARROW) {
2688                 return null;
2689             }
2690             String[] names;
2691             SoftReference<Map<Locale, String[]>> ref = cache.get(id);
2692             Map<Locale, String[]> perLocale;
2693             if (ref == null || (perLocale = ref.get()) == null ||
2694                 (names = perLocale.get(locale)) == null) {
2695                 names = TimeZoneNameUtility.retrieveDisplayNames(id, locale);
2696                 if (names == null) {
2697                     return null;
2698                 }
2699                 names = Arrays.copyOfRange(names, 0, 7);
2700                 names[5] =
2701                     TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.LONG,locale);
2702                 if (names[5] == null) {
2703                     names[5] = names[0]; // use the id
2704                 }
2705                 names[6] =
2706                     TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.SHORT,locale);
2707                 if (names[6] == null) {
2708                     names[6] = names[0];
2709                 }

2710                 perLocale = new ConcurrentHashMap<>();

2711                 perLocale.put(locale, names);
2712                 ref = new SoftReference<>(perLocale);
2713                 cache.put(id, ref);
2714             }
2715             switch (type) {
2716             case STD:
2717                 return names[style.ordinal() + 1];
2718             case DST:
2719                 return names[style.ordinal() + 3];
2720             }
2721             return names[style.ordinal() + 5];
2722         }
2723 
2724         @Override
2725         public boolean print(DateTimePrintContext context, StringBuilder buf) {
2726             ZoneId zone = context.getValue(Queries.zoneId());
2727             if (zone == null) {
2728                 return false;
2729             }
2730             if (zone instanceof ZoneOffset) {
2731                 buf.append(zone.getId());
2732             } else {
2733                 TemporalAccessor dt = context.getTemporal();
2734                 Instant instant = null;
2735                 if (dt.isSupported(ChronoField.INSTANT_SECONDS)) {
2736                     instant = Instant.from(dt);
2737                 }
2738                 String name = getDisplayName(zone.getId(),
2739                                              instant == null ? GENERIC
2740                                                              : (zone.getRules().isDaylightSavings(instant) ? DST : STD),
2741                     textStyle, context.getLocale());
2742                 if (name != null) {
2743                     buf.append(name);
2744                 } else {
2745                     buf.append(zone.getId());
2746                 }
2747             }

2748             return true;
2749         }
2750 






2751         @Override
2752         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2753             throw new UnsupportedOperationException();

2754         }




2755 
2756         @Override
2757         public String toString() {
2758             return "ZoneText(" + textStyle + ")";





































2759         }
2760     }
2761 
2762     //-----------------------------------------------------------------------
2763     /**
2764      * Prints or parses a zone ID.
2765      */
2766     static final class ZoneIdPrinterParser implements DateTimePrinterParser {
2767         private final TemporalQuery<ZoneId> query;
2768         private final String description;
2769 
2770         ZoneIdPrinterParser(TemporalQuery<ZoneId> query, String description) {
2771             this.query = query;
2772             this.description = description;
2773         }
2774 
2775         //-----------------------------------------------------------------------
2776         @Override
2777         public boolean print(DateTimePrintContext context, StringBuilder buf) {
2778             ZoneId zone = context.getValue(query);
2779             if (zone == null) {
2780                 return false;
2781             }
2782             buf.append(zone.getId());
2783             return true;
2784         }
2785 
2786         //-----------------------------------------------------------------------
2787         /**
2788          * The cached tree to speed up parsing.
2789          */
2790         private static volatile Entry<Integer, PrefixTree> cachedPrefixTree;
2791         private static volatile Entry<Integer, PrefixTree> cachedPrefixTreeCI;
2792 
2793         /**
2794          * This implementation looks for the longest matching string.
2795          * For example, parsing Etc/GMT-2 will return Etc/GMC-2 rather than just
2796          * Etc/GMC although both are valid.
2797          */
2798         @Override
2799         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2800             int length = text.length();
2801             if (position > length) {
2802                 throw new IndexOutOfBoundsException();
2803             }
2804 
2805             // handle fixed time-zone IDs
2806             if ((text.length() - position) >= 1) {
2807                 char nextChar = text.charAt(position);
2808                 if (nextChar == '+' || nextChar == '-') {
2809                     DateTimeParseContext newContext = context.copy();
2810                     int endPos = OffsetIdPrinterParser.INSTANCE_ID.parse(newContext, text, position);
2811                     if (endPos < 0) {
2812                         return endPos;
2813                     }
2814                     int offset = (int) (long) newContext.getParsed(OFFSET_SECONDS);
2815                     ZoneId zone = ZoneOffset.ofTotalSeconds(offset);
2816                     context.setParsed(zone);
2817                     return endPos;
2818                 }
2819             }
2820 
2821             // prepare parse tree
2822             Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
2823             final int regionIdsSize = regionIds.size();
2824             Entry<Integer, PrefixTree> cached = context.isCaseSensitive()
2825                                                 ? cachedPrefixTree : cachedPrefixTreeCI;
2826             if (cached == null || cached.getKey() != regionIdsSize) {
2827                 synchronized (this) {
2828                     cached = context.isCaseSensitive() ? cachedPrefixTree : cachedPrefixTreeCI;
2829                     if (cached == null || cached.getKey() != regionIdsSize) {
2830                         cached = new SimpleImmutableEntry<>(regionIdsSize,
2831                             PrefixTree.newTree(regionIds, context.isCaseSensitive()
2832                                                           ? PrefixTree.STRICT : PrefixTree.CASE_INSENSITIVE));
2833                         if (context.isCaseSensitive()) {
2834                             cachedPrefixTree = cached;
2835                         } else {
2836                             cachedPrefixTreeCI = cached;
2837                         }
2838                     }
2839                 }
2840             }
2841             PrefixTree tree = cached.getValue();

































2842 
2843             // parse
2844             String parsedZoneId = tree.match(text, position, length);
2845             if (parsedZoneId == null || regionIds.contains(parsedZoneId) == false) {
2846                 if (text.charAt(position) == 'Z') {


2847                     context.setParsed(ZoneOffset.UTC);
2848                     return position + 1;
2849                 }
2850                 return ~position;
2851             }
2852             context.setParsed(ZoneId.of(parsedZoneId));
2853             return position + parsedZoneId.length();
2854         }
2855 















2856 
2857         @Override
2858         public String toString() {
2859             return description;
2860         }
2861     }
2862 
2863     //-----------------------------------------------------------------------
2864     /**
2865      * A String based prefix tree for parsing time-zone names.
2866      */
2867     static class PrefixTree {
2868         protected String key;
2869         protected String value;
2870         protected char c0;    // performance optimization to avoid the
2871                               // boundary check cost of key.charat(0)
2872         protected PrefixTree child;
2873         protected PrefixTree sibling;
2874 
2875         static final int STRICT = 1;
2876         static final int CASE_INSENSITIVE = 2;
2877         static final int LENIENT = 3;
2878 
2879         private PrefixTree(String k, String v, PrefixTree child) {
2880             this.key = k;
2881             this.value = v;
2882             this.child = child;
2883             if (k.length() == 0){
2884                 c0 = 0xffff;
2885             } else {
2886                 c0 = key.charAt(0);
2887             }
2888         }
2889 
2890         /**
2891          * Creates a new prefix parsing tree.
2892          *
2893          * @param type  the type of the prefix tree. One of the three supported
2894          *  types, STRICT, CASE_INSENSITIVE and LENIENT
2895          * @return the tree, not null
2896          */
2897         public static PrefixTree newTree(int type) {
2898             PrefixTree tree;
2899             switch(type) {
2900                 case STRICT:
2901                     tree = new PrefixTree("", null, null);
2902                     break;
2903                 case CASE_INSENSITIVE:
2904                     tree = new CI("", null, null);
2905                     break;
2906                 case LENIENT:
2907                     tree = new LENIENT("", null, null);
2908                     break;
2909                 default:
2910                     throw new IllegalArgumentException("Unknown type");
2911             }
2912             return tree;
2913         }
2914 
2915         /**
2916          * Creates a new prefix parsing tree.
2917          *
2918          * @param keys  a set of strings to build the prefix parsing tree, not null
2919          * @param type  the type of the prefix tree. One of the three supported
2920          *  types, STRICT, CASE_INSENSITIVE and LENIENT
2921          * @return the tree, not null
2922          */
2923         public static  PrefixTree newTree(Set<String> keys, int type) {
2924             PrefixTree tree = newTree(type);
2925             for (String k : keys) {
2926                 tree.add0(k, k);
2927             }
2928             return tree;
2929         }
2930 
2931         /**















2932          * Adds a pair of {key, value} into the prefix tree.
2933          *
2934          * @param k  the key, not null
2935          * @param v  the value, not null
2936          * @return  true if the pair is added successfully
2937          */
2938         public boolean add(String k, String v) {
2939             return add0(k, v);
2940         }
2941 
2942         private boolean add0(String k, String v) {
2943             k = toKey(k);
2944             int prefixLen = prefixLength(k);
2945             if (prefixLen == key.length()) {
2946                 if (prefixLen < k.length()) {  // down the tree
2947                     String subKey = k.substring(prefixLen);
2948                     PrefixTree c = child;
2949                     while (c != null) {
2950                         if (isEqual(c.c0, subKey.charAt(0))) {
2951                             return c.add0(subKey, v);
2952                         }
2953                         c = c.sibling;
2954                     }
2955                     // add the node as the child of the current node
2956                     c = newNode(subKey, v, null);
2957                     c.sibling = child;
2958                     child = c;
2959                     return true;
2960                 }
2961                 // have an existing <key, value> already, keep it.
2962                 if (value != null) {
2963                     return false;
2964                 }
2965                 value = v;
2966                 return true;
2967             }
2968             // split the existing node
2969             PrefixTree n1 = newNode(key.substring(prefixLen), value, child);
2970             key = k.substring(0, prefixLen);
2971             child = n1;
2972             if (prefixLen < k.length()) {
2973                 PrefixTree n2 = newNode(k.substring(prefixLen), v, null);
2974                 child.sibling = n2;
2975                 value = null;
2976             } else {
2977                 value = v;
2978             }
2979             return true;
2980         }
2981 
2982         /**
2983          * Match text with the prefix tree.
2984          *


3080             }
3081             return off;
3082         }
3083 
3084         /**
3085          * Case Insensitive prefix tree.
3086          */
3087         private static class CI extends PrefixTree {
3088 
3089             private CI(String k, String v, PrefixTree child) {
3090                 super(k, v, child);
3091             }
3092 
3093             @Override
3094             protected CI newNode(String k, String v, PrefixTree child) {
3095                 return new CI(k, v, child);
3096             }
3097 
3098             @Override
3099             protected boolean isEqual(char c1, char c2) {
3100                 return c1 == c2 ||
3101                        Character.toUpperCase(c1) == Character.toUpperCase(c2) ||
3102                        Character.toLowerCase(c1) == Character.toLowerCase(c2);
3103             }
3104 
3105             @Override
3106             protected boolean prefixOf(CharSequence text, int off, int end) {
3107                 int len = key.length();
3108                 if (len > end - off) {
3109                     return false;
3110                 }
3111                 int off0 = 0;
3112                 while (len-- > 0) {
3113                     if (!isEqual(key.charAt(off0++), text.charAt(off++))) {
3114                         return false;
3115                     }
3116                 }
3117                 return true;
3118             }
3119         }
3120 
3121         /**
3122          * Lenient prefix tree. Case insensitive and ignores characters


3196                 pos.setIndex(off);
3197                 return value;
3198             }
3199         }
3200     }
3201 
3202     //-----------------------------------------------------------------------
3203     /**
3204      * Prints or parses a chronology.
3205      */
3206     static final class ChronoPrinterParser implements DateTimePrinterParser {
3207         /** The text style to output, null means the ID. */
3208         private final TextStyle textStyle;
3209 
3210         ChronoPrinterParser(TextStyle textStyle) {
3211             // validated by caller
3212             this.textStyle = textStyle;
3213         }
3214 
3215         @Override
3216         public boolean print(DateTimePrintContext context, StringBuilder buf) {
3217             Chrono<?> chrono = context.getValue(Queries.chrono());
3218             if (chrono == null) {
3219                 return false;
3220             }
3221             if (textStyle == null) {
3222                 buf.append(chrono.getId());
3223             } else {
3224                 buf.append(chrono.getId());  // TODO: Use symbols
3225             }
3226             return true;
3227         }
3228 
3229         @Override
3230         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3231             return ~position;  // TODO, including case insensitive



















3232         }
3233     }
3234 
3235     //-----------------------------------------------------------------------
3236     /**
3237      * Prints or parses a localized pattern.
3238      */
3239     static final class LocalizedPrinterParser implements DateTimePrinterParser {
3240         private final FormatStyle dateStyle;
3241         private final FormatStyle timeStyle;
3242         private final Chrono<?> chrono;
3243 
3244         /**
3245          * Constructor.
3246          *
3247          * @param dateStyle  the date style to use, may be null
3248          * @param timeStyle  the time style to use, may be null
3249          * @param chrono  the chronology to use, not null
3250          */
3251         LocalizedPrinterParser(FormatStyle dateStyle, FormatStyle timeStyle, Chrono<?> chrono) {
3252             // validated by caller
3253             this.dateStyle = dateStyle;
3254             this.timeStyle = timeStyle;
3255             this.chrono = chrono;
3256         }
3257 
3258         @Override
3259         public boolean print(DateTimePrintContext context, StringBuilder buf) {
3260             return formatter(context.getLocale()).toPrinterParser(false).print(context, buf);

3261         }
3262 
3263         @Override
3264         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3265             return formatter(context.getLocale()).toPrinterParser(false).parse(context, text, position);

3266         }
3267 
3268         /**
3269          * Gets the formatter to use.
3270          *
3271          * @param locale  the locale to use, not null

3272          * @return the formatter, not null
3273          * @throws IllegalArgumentException if the formatter cannot be found
3274          */
3275         private DateTimeFormatter formatter(Locale locale) {
3276             return DateTimeFormatStyleProvider.getInstance()
3277                                               .getFormatter(dateStyle, timeStyle, chrono, locale);
3278         }
3279 
3280         @Override
3281         public String toString() {
3282             return "Localized(" + (dateStyle != null ? dateStyle : "") + "," +
3283                 (timeStyle != null ? timeStyle : "") + "," + chrono.getId() + ")";
3284         }
3285     }
3286 
3287 
3288     //-----------------------------------------------------------------------
3289     /**
3290      * Prints or parses a localized pattern from a localized field.
3291      * The specific formatter and parameters is not selected until the
3292      * the field is to be printed or parsed.
3293      * The locale is needed to select the proper WeekFields from which
3294      * the field for day-of-week, week-of-month, or week-of-year is selected.
3295      */
3296     static final class WeekBasedFieldPrinterParser implements DateTimePrinterParser {
3297         private char chr;
3298         private int count;
3299 
3300         /**
3301          * Constructor.
3302          *
3303          * @param chr the pattern format letter that added this PrinterParser.
3304          * @param count the repeat count of the format letter
3305          */
3306         WeekBasedFieldPrinterParser(char chr, int count) {
3307             this.chr = chr;
3308             this.count = count;
3309         }
3310 
3311         @Override
3312         public boolean print(DateTimePrintContext context, StringBuilder buf) {
3313             return printerParser(context.getLocale()).print(context, buf);
3314         }
3315 
3316         @Override
3317         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3318             return printerParser(context.getLocale()).parse(context, text, position);
3319         }
3320 
3321         /**
3322          * Gets the printerParser to use based on the field and the locale.
3323          *
3324          * @param locale  the locale to use, not null
3325          * @return the formatter, not null
3326          * @throws IllegalArgumentException if the formatter cannot be found
3327          */
3328         private DateTimePrinterParser printerParser(Locale locale) {
3329             WeekFields weekDef = WeekFields.of(locale);
3330             TemporalField field = null;
3331             switch (chr) {
3332                 case 'e':
3333                     field = weekDef.dayOfWeek();




  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:


 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


 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      */


 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') {


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++;


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     //-----------------------------------------------------------------------


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     /**


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) {


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         }


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 + "'";


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         }


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     /**


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);


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();


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 


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


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++;


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          *


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


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();