1 /*
   2  * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time.format;
  63 
  64 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
  65 import static java.time.temporal.ChronoField.DAY_OF_WEEK;
  66 import static java.time.temporal.ChronoField.DAY_OF_YEAR;
  67 import static java.time.temporal.ChronoField.HOUR_OF_DAY;
  68 import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
  69 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  70 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
  71 import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
  72 import static java.time.temporal.ChronoField.YEAR;
  73 
  74 import java.io.IOException;
  75 import java.text.FieldPosition;
  76 import java.text.Format;
  77 import java.text.ParseException;
  78 import java.text.ParsePosition;
  79 import java.time.DateTimeException;
  80 import java.time.Period;
  81 import java.time.ZoneId;
  82 import java.time.ZoneOffset;
  83 import java.time.chrono.ChronoLocalDateTime;
  84 import java.time.chrono.Chronology;
  85 import java.time.chrono.IsoChronology;
  86 import java.time.format.DateTimeFormatterBuilder.CompositePrinterParser;
  87 import java.time.temporal.ChronoField;
  88 import java.time.temporal.IsoFields;
  89 import java.time.temporal.TemporalAccessor;
  90 import java.time.temporal.TemporalField;
  91 import java.time.temporal.TemporalQuery;
  92 import java.util.Arrays;
  93 import java.util.Collections;
  94 import java.util.HashMap;
  95 import java.util.HashSet;
  96 import java.util.Locale;
  97 import java.util.Map;
  98 import java.util.Objects;
  99 import java.util.Set;
 100 import sun.util.locale.provider.TimeZoneNameUtility;
 101 
 102 /**
 103  * Formatter for printing and parsing date-time objects.
 104  * <p>
 105  * This class provides the main application entry point for printing and parsing
 106  * and provides common implementations of {@code DateTimeFormatter}:
 107  * <ul>
 108  * <li>Using predefined constants, such as {@link #ISO_LOCAL_DATE}</li>
 109  * <li>Using pattern letters, such as {@code uuuu-MMM-dd}</li>
 110  * <li>Using localized styles, such as {@code long} or {@code medium}</li>
 111  * </ul>
 112  * <p>
 113  * More complex formatters are provided by
 114  * {@link DateTimeFormatterBuilder DateTimeFormatterBuilder}.
 115  *
 116  * <p>
 117  * The main date-time classes provide two methods - one for formatting,
 118  * {@code format(DateTimeFormatter formatter)}, and one for parsing,
 119  * {@code parse(CharSequence text, DateTimeFormatter formatter)}.
 120  * <p>For example:
 121  * <blockquote><pre>
 122  *  LocalDate date = LocalDate.now();
 123  *  String text = date.format(formatter);
 124  *  LocalDate parsedDate = LocalDate.parse(text, formatter);
 125  * </pre></blockquote>
 126  * <p>
 127  * In addition to the format, formatters can be created with desired Locale,
 128  * Chronology, ZoneId, and DecimalStyle.
 129  * <p>
 130  * The {@link #withLocale withLocale} method returns a new formatter that
 131  * overrides the locale. The locale affects some aspects of formatting and
 132  * parsing. For example, the {@link #ofLocalizedDate ofLocalizedDate} provides a
 133  * formatter that uses the locale specific date format.
 134  * <p>
 135  * The {@link #withChronology withChronology} method returns a new formatter
 136  * that overrides the chronology. If overridden, the date-time value is
 137  * converted to the chronology before formatting. During parsing the date-time
 138  * value is converted to the chronology before it is returned.
 139  * <p>
 140  * The {@link #withZone withZone} method returns a new formatter that overrides
 141  * the zone. If overridden, the date-time value is converted to a ZonedDateTime
 142  * with the requested ZoneId before formatting. During parsing the ZoneId is
 143  * applied before the value is returned.
 144  * <p>
 145  * The {@link #withDecimalStyle withDecimalStyle} method returns a new formatter that
 146  * overrides the {@link DecimalStyle}. The DecimalStyle symbols are used for
 147  * formatting and parsing.
 148  * <p>
 149  * Some applications may need to use the older {@link Format java.text.Format}
 150  * class for formatting. The {@link #toFormat()} method returns an
 151  * implementation of {@code java.text.Format}.
 152  *
 153  * <h2 id="predefined">Predefined Formatters</h2>
 154  * <table class="striped" style="text-align:left">
 155  * <caption>Predefined Formatters</caption>
 156  * <thead>
 157  * <tr>
 158  * <th scope="col">Formatter</th>
 159  * <th scope="col">Description</th>
 160  * <th scope="col">Example</th>
 161  * </tr>
 162  * </thead>
 163  * <tbody>
 164  * <tr>
 165  * <th scope="row">{@link #ofLocalizedDate ofLocalizedDate(dateStyle)} </th>
 166  * <td> Formatter with date style from the locale </td>
 167  * <td> '2011-12-03'</td>
 168  * </tr>
 169  * <tr>
 170  * <th scope="row"> {@link #ofLocalizedTime ofLocalizedTime(timeStyle)} </th>
 171  * <td> Formatter with time style from the locale </td>
 172  * <td> '10:15:30'</td>
 173  * </tr>
 174  * <tr>
 175  * <th scope="row"> {@link #ofLocalizedDateTime ofLocalizedDateTime(dateTimeStyle)} </th>
 176  * <td> Formatter with a style for date and time from the locale</td>
 177  * <td> '3 Jun 2008 11:05:30'</td>
 178  * </tr>
 179  * <tr>
 180  * <th scope="row"> {@link #ofLocalizedDateTime ofLocalizedDateTime(dateStyle,timeStyle)}
 181  * </th>
 182  * <td> Formatter with date and time styles from the locale </td>
 183  * <td> '3 Jun 2008 11:05'</td>
 184  * </tr>
 185  * <tr>
 186  * <th scope="row"> {@link #BASIC_ISO_DATE}</th>
 187  * <td>Basic ISO date </td> <td>'20111203'</td>
 188  * </tr>
 189  * <tr>
 190  * <th scope="row"> {@link #ISO_LOCAL_DATE}</th>
 191  * <td> ISO Local Date </td>
 192  * <td>'2011-12-03'</td>
 193  * </tr>
 194  * <tr>
 195  * <th scope="row"> {@link #ISO_OFFSET_DATE}</th>
 196  * <td> ISO Date with offset </td>
 197  * <td>'2011-12-03+01:00'</td>
 198  * </tr>
 199  * <tr>
 200  * <th scope="row"> {@link #ISO_DATE}</th>
 201  * <td> ISO Date with or without offset </td>
 202  * <td> '2011-12-03+01:00'; '2011-12-03'</td>
 203  * </tr>
 204  * <tr>
 205  * <th scope="row"> {@link #ISO_LOCAL_TIME}</th>
 206  * <td> Time without offset </td>
 207  * <td>'10:15:30'</td>
 208  * </tr>
 209  * <tr>
 210  * <th scope="row"> {@link #ISO_OFFSET_TIME}</th>
 211  * <td> Time with offset </td>
 212  * <td>'10:15:30+01:00'</td>
 213  * </tr>
 214  * <tr>
 215  * <th scope="row"> {@link #ISO_TIME}</th>
 216  * <td> Time with or without offset </td>
 217  * <td>'10:15:30+01:00'; '10:15:30'</td>
 218  * </tr>
 219  * <tr>
 220  * <th scope="row"> {@link #ISO_LOCAL_DATE_TIME}</th>
 221  * <td> ISO Local Date and Time </td>
 222  * <td>'2011-12-03T10:15:30'</td>
 223  * </tr>
 224  * <tr>
 225  * <th scope="row"> {@link #ISO_OFFSET_DATE_TIME}</th>
 226  * <td> Date Time with Offset
 227  * </td><td>'2011-12-03T10:15:30+01:00'</td>
 228  * </tr>
 229  * <tr>
 230  * <th scope="row"> {@link #ISO_ZONED_DATE_TIME}</th>
 231  * <td> Zoned Date Time </td>
 232  * <td>'2011-12-03T10:15:30+01:00[Europe/Paris]'</td>
 233  * </tr>
 234  * <tr>
 235  * <th scope="row"> {@link #ISO_DATE_TIME}</th>
 236  * <td> Date and time with ZoneId </td>
 237  * <td>'2011-12-03T10:15:30+01:00[Europe/Paris]'</td>
 238  * </tr>
 239  * <tr>
 240  * <th scope="row"> {@link #ISO_ORDINAL_DATE}</th>
 241  * <td> Year and day of year </td>
 242  * <td>'2012-337'</td>
 243  * </tr>
 244  * <tr>
 245  * <th scope="row"> {@link #ISO_WEEK_DATE}</th>
 246  * <td> Year and Week </td>
 247  * <td>'2012-W48-6'</td></tr>
 248  * <tr>
 249  * <th scope="row"> {@link #ISO_INSTANT}</th>
 250  * <td> Date and Time of an Instant </td>
 251  * <td>'2011-12-03T10:15:30Z' </td>
 252  * </tr>
 253  * <tr>
 254  * <th scope="row"> {@link #RFC_1123_DATE_TIME}</th>
 255  * <td> RFC 1123 / RFC 822 </td>
 256  * <td>'Tue, 3 Jun 2008 11:05:30 GMT'</td>
 257  * </tr>
 258  * </tbody>
 259  * </table>
 260  *
 261  * <h2 id="patterns">Patterns for Formatting and Parsing</h2>
 262  * Patterns are based on a simple sequence of letters and symbols.
 263  * A pattern is used to create a Formatter using the
 264  * {@link #ofPattern(String)} and {@link #ofPattern(String, Locale)} methods.
 265  * For example,
 266  * {@code "d MMM uuuu"} will format 2011-12-03 as '3&nbsp;Dec&nbsp;2011'.
 267  * A formatter created from a pattern can be used as many times as necessary,
 268  * it is immutable and is thread-safe.
 269  * <p>
 270  * For example:
 271  * <blockquote><pre>
 272  *  LocalDate date = LocalDate.now();
 273  *  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
 274  *  String text = date.format(formatter);
 275  *  LocalDate parsedDate = LocalDate.parse(text, formatter);
 276  * </pre></blockquote>
 277  * <p>
 278  * All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The
 279  * following pattern letters are defined:
 280  * <table class="striped">
 281  * <caption>Pattern Letters and Symbols</caption>
 282  * <thead>
 283  *  <tr><th scope="col">Symbol</th>   <th scope="col">Meaning</th>         <th scope="col">Presentation</th> <th scope="col">Examples</th>
 284  * </thead>
 285  * <tbody>
 286  *   <tr><th scope="row">G</th>       <td>era</td>                         <td>text</td>              <td>AD; Anno Domini; A</td>
 287  *   <tr><th scope="row">u</th>       <td>year</td>                        <td>year</td>              <td>2004; 04</td>
 288  *   <tr><th scope="row">y</th>       <td>year-of-era</td>                 <td>year</td>              <td>2004; 04</td>
 289  *   <tr><th scope="row">D</th>       <td>day-of-year</td>                 <td>number</td>            <td>189</td>
 290  *   <tr><th scope="row">M/L</th>     <td>month-of-year</td>               <td>number/text</td>       <td>7; 07; Jul; July; J</td>
 291  *   <tr><th scope="row">d</th>       <td>day-of-month</td>                <td>number</td>            <td>10</td>
 292  *   <tr><th scope="row">g</th>       <td>modified-julian-day</td>         <td>number</td>            <td>2451334</td>
 293  *
 294  *   <tr><th scope="row">Q/q</th>     <td>quarter-of-year</td>             <td>number/text</td>       <td>3; 03; Q3; 3rd quarter</td>
 295  *   <tr><th scope="row">Y</th>       <td>week-based-year</td>             <td>year</td>              <td>1996; 96</td>
 296  *   <tr><th scope="row">w</th>       <td>week-of-week-based-year</td>     <td>number</td>            <td>27</td>
 297  *   <tr><th scope="row">W</th>       <td>week-of-month</td>               <td>number</td>            <td>4</td>
 298  *   <tr><th scope="row">E</th>       <td>day-of-week</td>                 <td>text</td>              <td>Tue; Tuesday; T</td>
 299  *   <tr><th scope="row">e/c</th>     <td>localized day-of-week</td>       <td>number/text</td>       <td>2; 02; Tue; Tuesday; T</td>
 300  *   <tr><th scope="row">F</th>       <td>day-of-week-in-month</td>        <td>number</td>            <td>3</td>
 301  *
 302  *   <tr><th scope="row">a</th>       <td>am-pm-of-day</td>                <td>text</td>              <td>PM</td>
 303  *   <tr><th scope="row">h</th>       <td>clock-hour-of-am-pm (1-12)</td>  <td>number</td>            <td>12</td>
 304  *   <tr><th scope="row">K</th>       <td>hour-of-am-pm (0-11)</td>        <td>number</td>            <td>0</td>
 305  *   <tr><th scope="row">k</th>       <td>clock-hour-of-day (1-24)</td>    <td>number</td>            <td>24</td>
 306  *
 307  *   <tr><th scope="row">H</th>       <td>hour-of-day (0-23)</td>          <td>number</td>            <td>0</td>
 308  *   <tr><th scope="row">m</th>       <td>minute-of-hour</td>              <td>number</td>            <td>30</td>
 309  *   <tr><th scope="row">s</th>       <td>second-of-minute</td>            <td>number</td>            <td>55</td>
 310  *   <tr><th scope="row">S</th>       <td>fraction-of-second</td>          <td>fraction</td>          <td>978</td>
 311  *   <tr><th scope="row">A</th>       <td>milli-of-day</td>                <td>number</td>            <td>1234</td>
 312  *   <tr><th scope="row">n</th>       <td>nano-of-second</td>              <td>number</td>            <td>987654321</td>
 313  *   <tr><th scope="row">N</th>       <td>nano-of-day</td>                 <td>number</td>            <td>1234000000</td>
 314  *
 315  *   <tr><th scope="row">V</th>       <td>time-zone ID</td>                <td>zone-id</td>           <td>America/Los_Angeles; Z; -08:30</td>
 316  *   <tr><th scope="row">v</th>       <td>generic time-zone name</td>      <td>zone-name</td>         <td>Pacific Time; PT</td>
 317  *   <tr><th scope="row">z</th>       <td>time-zone name</td>              <td>zone-name</td>         <td>Pacific Standard Time; PST</td>
 318  *   <tr><th scope="row">O</th>       <td>localized zone-offset</td>       <td>offset-O</td>          <td>GMT+8; GMT+08:00; UTC-08:00</td>
 319  *   <tr><th scope="row">X</th>       <td>zone-offset 'Z' for zero</td>    <td>offset-X</td>          <td>Z; -08; -0830; -08:30; -083015; -08:30:15</td>
 320  *   <tr><th scope="row">x</th>       <td>zone-offset</td>                 <td>offset-x</td>          <td>+0000; -08; -0830; -08:30; -083015; -08:30:15</td>
 321  *   <tr><th scope="row">Z</th>       <td>zone-offset</td>                 <td>offset-Z</td>          <td>+0000; -0800; -08:00</td>
 322  *
 323  *   <tr><th scope="row">p</th>       <td>pad next</td>                    <td>pad modifier</td>      <td>1</td>
 324  *
 325  *   <tr><th scope="row">'</th>       <td>escape for text</td>             <td>delimiter</td>         <td></td>
 326  *   <tr><th scope="row">''</th>      <td>single quote</td>                <td>literal</td>           <td>'</td>
 327  *   <tr><th scope="row">[</th>       <td>optional section start</td>      <td></td>                  <td></td>
 328  *   <tr><th scope="row">]</th>       <td>optional section end</td>        <td></td>                  <td></td>
 329  *   <tr><th scope="row">#</th>       <td>reserved for future use</td>     <td></td>                  <td></td>
 330  *   <tr><th scope="row">{</th>       <td>reserved for future use</td>     <td></td>                  <td></td>
 331  *   <tr><th scope="row">}</th>       <td>reserved for future use</td>     <td></td>                  <td></td>
 332  * </tbody>
 333  * </table>
 334  * <p>
 335  * The count of pattern letters determines the format.
 336  * <p>
 337  * <b>Text</b>: The text style is determined based on the number of pattern
 338  * letters used. Less than 4 pattern letters will use the
 339  * {@link TextStyle#SHORT short form}. Exactly 4 pattern letters will use the
 340  * {@link TextStyle#FULL full form}. Exactly 5 pattern letters will use the
 341  * {@link TextStyle#NARROW narrow form}.
 342  * Pattern letters 'L', 'c', and 'q' specify the stand-alone form of the text styles.
 343  * <p>
 344  * <b>Number</b>: If the count of letters is one, then the value is output using
 345  * the minimum number of digits and without padding. Otherwise, the count of digits
 346  * is used as the width of the output field, with the value zero-padded as necessary.
 347  * The following pattern letters have constraints on the count of letters.
 348  * Only one letter of 'c' and 'F' can be specified.
 349  * Up to two letters of 'd', 'H', 'h', 'K', 'k', 'm', and 's' can be specified.
 350  * Up to three letters of 'D' can be specified.
 351  * <p>
 352  * <b>Number/Text</b>: If the count of pattern letters is 3 or greater, use the
 353  * Text rules above. Otherwise use the Number rules above.
 354  * <p>
 355  * <b>Fraction</b>: Outputs the nano-of-second field as a fraction-of-second.
 356  * The nano-of-second value has nine digits, thus the count of pattern letters
 357  * is from 1 to 9. If it is less than 9, then the nano-of-second value is
 358  * truncated, with only the most significant digits being output.
 359  * <p>
 360  * <b>Year</b>: The count of letters determines the minimum field width below
 361  * which padding is used. If the count of letters is two, then a
 362  * {@link DateTimeFormatterBuilder#appendValueReduced reduced} two digit form is
 363  * used. For printing, this outputs the rightmost two digits. For parsing, this
 364  * will parse using the base value of 2000, resulting in a year within the range
 365  * 2000 to 2099 inclusive. If the count of letters is less than four (but not
 366  * two), then the sign is only output for negative years as per
 367  * {@link SignStyle#NORMAL}. Otherwise, the sign is output if the pad width is
 368  * exceeded, as per {@link SignStyle#EXCEEDS_PAD}.
 369  * <p>
 370  * <b>ZoneId</b>: This outputs the time-zone ID, such as 'Europe/Paris'. If the
 371  * count of letters is two, then the time-zone ID is output. Any other count of
 372  * letters throws {@code IllegalArgumentException}.
 373  * <p>
 374  * <b>Zone names</b>: This outputs the display name of the time-zone ID. If the
 375  * pattern letter is 'z' the output is the daylight savings aware zone name.
 376  * If there is insufficient information to determine whether DST applies,
 377  * the name ignoring daylight savings time will be used.
 378  * If the count of letters is one, two or three, then the short name is output.
 379  * If the count of letters is four, then the full name is output.
 380  * Five or more letters throws {@code IllegalArgumentException}.
 381  * <p>
 382  * If the pattern letter is 'v' the output provides the zone name ignoring
 383  * daylight savings time. If the count of letters is one, then the short name is output.
 384  * If the count of letters is four, then the full name is output.
 385  * Two, three and five or more letters throw {@code IllegalArgumentException}.
 386  * <p>
 387  * <b>Offset X and x</b>: This formats the offset based on the number of pattern
 388  * letters. One letter outputs just the hour, such as '+01', unless the minute
 389  * is non-zero in which case the minute is also output, such as '+0130'. Two
 390  * letters outputs the hour and minute, without a colon, such as '+0130'. Three
 391  * letters outputs the hour and minute, with a colon, such as '+01:30'. Four
 392  * letters outputs the hour and minute and optional second, without a colon,
 393  * such as '+013015'. Five letters outputs the hour and minute and optional
 394  * second, with a colon, such as '+01:30:15'. Six or more letters throws
 395  * {@code IllegalArgumentException}. Pattern letter 'X' (upper case) will output
 396  * 'Z' when the offset to be output would be zero, whereas pattern letter 'x'
 397  * (lower case) will output '+00', '+0000', or '+00:00'.
 398  * <p>
 399  * <b>Offset O</b>: With a non-zero offset, this formats the localized offset
 400  * based on the number of pattern letters. One letter outputs the
 401  * {@linkplain TextStyle#SHORT short} form of the localized offset, which is
 402  * localized offset text, such as 'GMT', with hour without leading zero, optional
 403  * 2-digit minute and second if non-zero, and colon, for example 'GMT+8'. Four
 404  * letters outputs the {@linkplain TextStyle#FULL full} form, which is localized
 405  * offset text, such as 'GMT, with 2-digit hour and minute field, optional second
 406  * field if non-zero, and colon, for example 'GMT+08:00'. If the offset is zero,
 407  * only localized text is output. Any other count of letters throws
 408  * {@code IllegalArgumentException}.
 409  * <p>
 410  * <b>Offset Z</b>: This formats the offset based on the number of pattern
 411  * letters. One, two or three letters outputs the hour and minute, without a
 412  * colon, such as '+0130'. The output will be '+0000' when the offset is zero.
 413  * Four letters outputs the {@linkplain TextStyle#FULL full} form of localized
 414  * offset, equivalent to four letters of Offset-O. The output will be the
 415  * corresponding localized offset text if the offset is zero. Five
 416  * letters outputs the hour, minute, with optional second if non-zero, with
 417  * colon. It outputs 'Z' if the offset is zero.
 418  * Six or more letters throws {@code IllegalArgumentException}.
 419  * <p>
 420  * <b>Optional section</b>: The optional section markers work exactly like
 421  * calling {@link DateTimeFormatterBuilder#optionalStart()} and
 422  * {@link DateTimeFormatterBuilder#optionalEnd()}.
 423  * <p>
 424  * <b>Pad modifier</b>: Modifies the pattern that immediately follows to be
 425  * padded with spaces. The pad width is determined by the number of pattern
 426  * letters. This is the same as calling
 427  * {@link DateTimeFormatterBuilder#padNext(int)}.
 428  * <p>
 429  * For example, 'ppH' outputs the hour-of-day padded on the left with spaces to
 430  * a width of 2.
 431  * <p>
 432  * Any unrecognized letter is an error. Any non-letter character, other than
 433  * '[', ']', '{', '}', '#' and the single quote will be output directly.
 434  * Despite this, it is recommended to use single quotes around all characters
 435  * that you want to output directly to ensure that future changes do not break
 436  * your application.
 437  *
 438  * <h2 id="resolving">Resolving</h2>
 439  * Parsing is implemented as a two-phase operation.
 440  * First, the text is parsed using the layout defined by the formatter, producing
 441  * a {@code Map} of field to value, a {@code ZoneId} and a {@code Chronology}.
 442  * Second, the parsed data is <em>resolved</em>, by validating, combining and
 443  * simplifying the various fields into more useful ones.
 444  * <p>
 445  * Five parsing methods are supplied by this class.
 446  * Four of these perform both the parse and resolve phases.
 447  * The fifth method, {@link #parseUnresolved(CharSequence, ParsePosition)},
 448  * only performs the first phase, leaving the result unresolved.
 449  * As such, it is essentially a low-level operation.
 450  * <p>
 451  * The resolve phase is controlled by two parameters, set on this class.
 452  * <p>
 453  * The {@link ResolverStyle} is an enum that offers three different approaches,
 454  * strict, smart and lenient. The smart option is the default.
 455  * It can be set using {@link #withResolverStyle(ResolverStyle)}.
 456  * <p>
 457  * The {@link #withResolverFields(TemporalField...)} parameter allows the
 458  * set of fields that will be resolved to be filtered before resolving starts.
 459  * For example, if the formatter has parsed a year, month, day-of-month
 460  * and day-of-year, then there are two approaches to resolve a date:
 461  * (year + month + day-of-month) and (year + day-of-year).
 462  * The resolver fields allows one of the two approaches to be selected.
 463  * If no resolver fields are set then both approaches must result in the same date.
 464  * <p>
 465  * Resolving separate fields to form a complete date and time is a complex
 466  * process with behaviour distributed across a number of classes.
 467  * It follows these steps:
 468  * <ol>
 469  * <li>The chronology is determined.
 470  * The chronology of the result is either the chronology that was parsed,
 471  * or if no chronology was parsed, it is the chronology set on this class,
 472  * or if that is null, it is {@code IsoChronology}.
 473  * <li>The {@code ChronoField} date fields are resolved.
 474  * This is achieved using {@link Chronology#resolveDate(Map, ResolverStyle)}.
 475  * Documentation about field resolution is located in the implementation
 476  * of {@code Chronology}.
 477  * <li>The {@code ChronoField} time fields are resolved.
 478  * This is documented on {@link ChronoField} and is the same for all chronologies.
 479  * <li>Any fields that are not {@code ChronoField} are processed.
 480  * This is achieved using {@link TemporalField#resolve(Map, TemporalAccessor, ResolverStyle)}.
 481  * Documentation about field resolution is located in the implementation
 482  * of {@code TemporalField}.
 483  * <li>The {@code ChronoField} date and time fields are re-resolved.
 484  * This allows fields in step four to produce {@code ChronoField} values
 485  * and have them be processed into dates and times.
 486  * <li>A {@code LocalTime} is formed if there is at least an hour-of-day available.
 487  * This involves providing default values for minute, second and fraction of second.
 488  * <li>Any remaining unresolved fields are cross-checked against any
 489  * date and/or time that was resolved. Thus, an earlier stage would resolve
 490  * (year + month + day-of-month) to a date, and this stage would check that
 491  * day-of-week was valid for the date.
 492  * <li>If an {@linkplain #parsedExcessDays() excess number of days}
 493  * was parsed then it is added to the date if a date is available.
 494  * <li> If a second-based field is present, but {@code LocalTime} was not parsed,
 495  * then the resolver ensures that milli, micro and nano second values are
 496  * available to meet the contract of {@link ChronoField}.
 497  * These will be set to zero if missing.
 498  * <li>If both date and time were parsed and either an offset or zone is present,
 499  * the field {@link ChronoField#INSTANT_SECONDS} is created.
 500  * If an offset was parsed then the offset will be combined with the
 501  * {@code LocalDateTime} to form the instant, with any zone ignored.
 502  * If a {@code ZoneId} was parsed without an offset then the zone will be
 503  * combined with the {@code LocalDateTime} to form the instant using the rules
 504  * of {@link ChronoLocalDateTime#atZone(ZoneId)}.
 505  * </ol>
 506  *
 507  * @implSpec
 508  * This class is immutable and thread-safe.
 509  *
 510  * @since 1.8
 511  */
 512 public final class DateTimeFormatter {
 513 
 514     /**
 515      * The printer and/or parser to use, not null.
 516      */
 517     private final CompositePrinterParser printerParser;
 518     /**
 519      * The locale to use for formatting, not null.
 520      */
 521     private final Locale locale;
 522     /**
 523      * The symbols to use for formatting, not null.
 524      */
 525     private final DecimalStyle decimalStyle;
 526     /**
 527      * The resolver style to use, not null.
 528      */
 529     private final ResolverStyle resolverStyle;
 530     /**
 531      * The fields to use in resolving, null for all fields.
 532      */
 533     private final Set<TemporalField> resolverFields;
 534     /**
 535      * The chronology to use for formatting, null for no override.
 536      */
 537     private final Chronology chrono;
 538     /**
 539      * The zone to use for formatting, null for no override.
 540      */
 541     private final ZoneId zone;
 542 
 543     //-----------------------------------------------------------------------
 544     /**
 545      * Creates a formatter using the specified pattern.
 546      * <p>
 547      * This method will create a formatter based on a simple
 548      * <a href="#patterns">pattern of letters and symbols</a>
 549      * as described in the class documentation.
 550      * For example, {@code d MMM uuuu} will format 2011-12-03 as '3 Dec 2011'.
 551      * <p>
 552      * The formatter will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}.
 553      * This can be changed using {@link DateTimeFormatter#withLocale(Locale)} on the returned formatter.
 554      * Alternatively use the {@link #ofPattern(String, Locale)} variant of this method.
 555      * <p>
 556      * The returned formatter has no override chronology or zone.
 557      * It uses {@link ResolverStyle#SMART SMART} resolver style.
 558      *
 559      * @param pattern  the pattern to use, not null
 560      * @return the formatter based on the pattern, not null
 561      * @throws IllegalArgumentException if the pattern is invalid
 562      * @see DateTimeFormatterBuilder#appendPattern(String)
 563      */
 564     public static DateTimeFormatter ofPattern(String pattern) {
 565         return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter();
 566     }
 567 
 568     /**
 569      * Creates a formatter using the specified pattern and locale.
 570      * <p>
 571      * This method will create a formatter based on a simple
 572      * <a href="#patterns">pattern of letters and symbols</a>
 573      * as described in the class documentation.
 574      * For example, {@code d MMM uuuu} will format 2011-12-03 as '3 Dec 2011'.
 575      * <p>
 576      * The formatter will use the specified locale.
 577      * This can be changed using {@link DateTimeFormatter#withLocale(Locale)} on the returned formatter.
 578      * <p>
 579      * The returned formatter has no override chronology or zone.
 580      * It uses {@link ResolverStyle#SMART SMART} resolver style.
 581      *
 582      * @param pattern  the pattern to use, not null
 583      * @param locale  the locale to use, not null
 584      * @return the formatter based on the pattern, not null
 585      * @throws IllegalArgumentException if the pattern is invalid
 586      * @see DateTimeFormatterBuilder#appendPattern(String)
 587      */
 588     public static DateTimeFormatter ofPattern(String pattern, Locale locale) {
 589         return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(locale);
 590     }
 591 
 592     //-----------------------------------------------------------------------
 593     /**
 594      * Returns a locale specific date format for the ISO chronology.
 595      * <p>
 596      * This returns a formatter that will format or parse a date.
 597      * The exact format pattern used varies by locale.
 598      * <p>
 599      * The locale is determined from the formatter. The formatter returned directly by
 600      * this method will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}.
 601      * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
 602      * on the result of this method.
 603      * <p>
 604      * Note that the localized pattern is looked up lazily.
 605      * This {@code DateTimeFormatter} holds the style required and the locale,
 606      * looking up the pattern required on demand.
 607      * <p>
 608      * The returned formatter has a chronology of ISO set to ensure dates in
 609      * other calendar systems are correctly converted.
 610      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
 611      *
 612      * @param dateStyle  the formatter style to obtain, not null
 613      * @return the date formatter, not null
 614      */
 615     public static DateTimeFormatter ofLocalizedDate(FormatStyle dateStyle) {
 616         Objects.requireNonNull(dateStyle, "dateStyle");
 617         return new DateTimeFormatterBuilder().appendLocalized(dateStyle, null)
 618                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
 619     }
 620 
 621     /**
 622      * Returns a locale specific time format for the ISO chronology.
 623      * <p>
 624      * This returns a formatter that will format or parse a time.
 625      * The exact format pattern used varies by locale.
 626      * <p>
 627      * The locale is determined from the formatter. The formatter returned directly by
 628      * this method will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}.
 629      * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
 630      * on the result of this method.
 631      * <p>
 632      * Note that the localized pattern is looked up lazily.
 633      * This {@code DateTimeFormatter} holds the style required and the locale,
 634      * looking up the pattern required on demand.
 635      * <p>
 636      * The returned formatter has a chronology of ISO set to ensure dates in
 637      * other calendar systems are correctly converted.
 638      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
 639      * The {@code FULL} and {@code LONG} styles typically require a time-zone.
 640      * When formatting using these styles, a {@code ZoneId} must be available,
 641      * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}.
 642      *
 643      * @param timeStyle  the formatter style to obtain, not null
 644      * @return the time formatter, not null
 645      */
 646     public static DateTimeFormatter ofLocalizedTime(FormatStyle timeStyle) {
 647         Objects.requireNonNull(timeStyle, "timeStyle");
 648         return new DateTimeFormatterBuilder().appendLocalized(null, timeStyle)
 649                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
 650     }
 651 
 652     /**
 653      * Returns a locale specific date-time formatter for the ISO chronology.
 654      * <p>
 655      * This returns a formatter that will format or parse a date-time.
 656      * The exact format pattern used varies by locale.
 657      * <p>
 658      * The locale is determined from the formatter. The formatter returned directly by
 659      * this method will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}.
 660      * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
 661      * on the result of this method.
 662      * <p>
 663      * Note that the localized pattern is looked up lazily.
 664      * This {@code DateTimeFormatter} holds the style required and the locale,
 665      * looking up the pattern required on demand.
 666      * <p>
 667      * The returned formatter has a chronology of ISO set to ensure dates in
 668      * other calendar systems are correctly converted.
 669      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
 670      * The {@code FULL} and {@code LONG} styles typically require a time-zone.
 671      * When formatting using these styles, a {@code ZoneId} must be available,
 672      * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}.
 673      *
 674      * @param dateTimeStyle  the formatter style to obtain, not null
 675      * @return the date-time formatter, not null
 676      */
 677     public static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateTimeStyle) {
 678         Objects.requireNonNull(dateTimeStyle, "dateTimeStyle");
 679         return new DateTimeFormatterBuilder().appendLocalized(dateTimeStyle, dateTimeStyle)
 680                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
 681     }
 682 
 683     /**
 684      * Returns a locale specific date and time format for the ISO chronology.
 685      * <p>
 686      * This returns a formatter that will format or parse a date-time.
 687      * The exact format pattern used varies by locale.
 688      * <p>
 689      * The locale is determined from the formatter. The formatter returned directly by
 690      * this method will use the {@link Locale#getDefault() default FORMAT locale}.
 691      * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
 692      * on the result of this method.
 693      * <p>
 694      * Note that the localized pattern is looked up lazily.
 695      * This {@code DateTimeFormatter} holds the style required and the locale,
 696      * looking up the pattern required on demand.
 697      * <p>
 698      * The returned formatter has a chronology of ISO set to ensure dates in
 699      * other calendar systems are correctly converted.
 700      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
 701      * The {@code FULL} and {@code LONG} styles typically require a time-zone.
 702      * When formatting using these styles, a {@code ZoneId} must be available,
 703      * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}.
 704      *
 705      * @param dateStyle  the date formatter style to obtain, not null
 706      * @param timeStyle  the time formatter style to obtain, not null
 707      * @return the date, time or date-time formatter, not null
 708      */
 709     public static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle) {
 710         Objects.requireNonNull(dateStyle, "dateStyle");
 711         Objects.requireNonNull(timeStyle, "timeStyle");
 712         return new DateTimeFormatterBuilder().appendLocalized(dateStyle, timeStyle)
 713                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
 714     }
 715 
 716     //-----------------------------------------------------------------------
 717     /**
 718      * The ISO date formatter that formats or parses a date without an
 719      * offset, such as '2011-12-03'.
 720      * <p>
 721      * This returns an immutable formatter capable of formatting and parsing
 722      * the ISO-8601 extended local date format.
 723      * The format consists of:
 724      * <ul>
 725      * <li>Four digits or more for the {@link ChronoField#YEAR year}.
 726      * Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits.
 727      * Years outside that range will have a prefixed positive or negative symbol.
 728      * <li>A dash
 729      * <li>Two digits for the {@link ChronoField#MONTH_OF_YEAR month-of-year}.
 730      *  This is pre-padded by zero to ensure two digits.
 731      * <li>A dash
 732      * <li>Two digits for the {@link ChronoField#DAY_OF_MONTH day-of-month}.
 733      *  This is pre-padded by zero to ensure two digits.
 734      * </ul>
 735      * <p>
 736      * The returned formatter has a chronology of ISO set to ensure dates in
 737      * other calendar systems are correctly converted.
 738      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 739      */
 740     public static final DateTimeFormatter ISO_LOCAL_DATE;
 741     static {
 742         ISO_LOCAL_DATE = new DateTimeFormatterBuilder()
 743                 .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
 744                 .appendLiteral('-')
 745                 .appendValue(MONTH_OF_YEAR, 2)
 746                 .appendLiteral('-')
 747                 .appendValue(DAY_OF_MONTH, 2)
 748                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
 749     }
 750 
 751     //-----------------------------------------------------------------------
 752     /**
 753      * The ISO date formatter that formats or parses a date with an
 754      * offset, such as '2011-12-03+01:00'.
 755      * <p>
 756      * This returns an immutable formatter capable of formatting and parsing
 757      * the ISO-8601 extended offset date format.
 758      * The format consists of:
 759      * <ul>
 760      * <li>The {@link #ISO_LOCAL_DATE}
 761      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
 762      *  they will be handled even though this is not part of the ISO-8601 standard.
 763      *  Parsing is case insensitive.
 764      * </ul>
 765      * <p>
 766      * The returned formatter has a chronology of ISO set to ensure dates in
 767      * other calendar systems are correctly converted.
 768      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 769      */
 770     public static final DateTimeFormatter ISO_OFFSET_DATE;
 771     static {
 772         ISO_OFFSET_DATE = new DateTimeFormatterBuilder()
 773                 .parseCaseInsensitive()
 774                 .append(ISO_LOCAL_DATE)
 775                 .appendOffsetId()
 776                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
 777     }
 778 
 779     //-----------------------------------------------------------------------
 780     /**
 781      * The ISO date formatter that formats or parses a date with the
 782      * offset if available, such as '2011-12-03' or '2011-12-03+01:00'.
 783      * <p>
 784      * This returns an immutable formatter capable of formatting and parsing
 785      * the ISO-8601 extended date format.
 786      * The format consists of:
 787      * <ul>
 788      * <li>The {@link #ISO_LOCAL_DATE}
 789      * <li>If the offset is not available then the format is complete.
 790      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
 791      *  they will be handled even though this is not part of the ISO-8601 standard.
 792      *  Parsing is case insensitive.
 793      * </ul>
 794      * <p>
 795      * As this formatter has an optional element, it may be necessary to parse using
 796      * {@link DateTimeFormatter#parseBest}.
 797      * <p>
 798      * The returned formatter has a chronology of ISO set to ensure dates in
 799      * other calendar systems are correctly converted.
 800      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 801      */
 802     public static final DateTimeFormatter ISO_DATE;
 803     static {
 804         ISO_DATE = new DateTimeFormatterBuilder()
 805                 .parseCaseInsensitive()
 806                 .append(ISO_LOCAL_DATE)
 807                 .optionalStart()
 808                 .appendOffsetId()
 809                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
 810     }
 811 
 812     //-----------------------------------------------------------------------
 813     /**
 814      * The ISO time formatter that formats or parses a time without an
 815      * offset, such as '10:15' or '10:15:30'.
 816      * <p>
 817      * This returns an immutable formatter capable of formatting and parsing
 818      * the ISO-8601 extended local time format.
 819      * The format consists of:
 820      * <ul>
 821      * <li>Two digits for the {@link ChronoField#HOUR_OF_DAY hour-of-day}.
 822      *  This is pre-padded by zero to ensure two digits.
 823      * <li>A colon
 824      * <li>Two digits for the {@link ChronoField#MINUTE_OF_HOUR minute-of-hour}.
 825      *  This is pre-padded by zero to ensure two digits.
 826      * <li>If the second-of-minute is not available then the format is complete.
 827      * <li>A colon
 828      * <li>Two digits for the {@link ChronoField#SECOND_OF_MINUTE second-of-minute}.
 829      *  This is pre-padded by zero to ensure two digits.
 830      * <li>If the nano-of-second is zero or not available then the format is complete.
 831      * <li>A decimal point
 832      * <li>One to nine digits for the {@link ChronoField#NANO_OF_SECOND nano-of-second}.
 833      *  As many digits will be output as required.
 834      * </ul>
 835      * <p>
 836      * The returned formatter has no override chronology or zone.
 837      * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 838      */
 839     public static final DateTimeFormatter ISO_LOCAL_TIME;
 840     static {
 841         ISO_LOCAL_TIME = new DateTimeFormatterBuilder()
 842                 .appendValue(HOUR_OF_DAY, 2)
 843                 .appendLiteral(':')
 844                 .appendValue(MINUTE_OF_HOUR, 2)
 845                 .optionalStart()
 846                 .appendLiteral(':')
 847                 .appendValue(SECOND_OF_MINUTE, 2)
 848                 .optionalStart()
 849                 .appendFraction(NANO_OF_SECOND, 0, 9, true)
 850                 .toFormatter(ResolverStyle.STRICT, null);
 851     }
 852 
 853     //-----------------------------------------------------------------------
 854     /**
 855      * The ISO time formatter that formats or parses a time with an
 856      * offset, such as '10:15+01:00' or '10:15:30+01:00'.
 857      * <p>
 858      * This returns an immutable formatter capable of formatting and parsing
 859      * the ISO-8601 extended offset time format.
 860      * The format consists of:
 861      * <ul>
 862      * <li>The {@link #ISO_LOCAL_TIME}
 863      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
 864      *  they will be handled even though this is not part of the ISO-8601 standard.
 865      *  Parsing is case insensitive.
 866      * </ul>
 867      * <p>
 868      * The returned formatter has no override chronology or zone.
 869      * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 870      */
 871     public static final DateTimeFormatter ISO_OFFSET_TIME;
 872     static {
 873         ISO_OFFSET_TIME = new DateTimeFormatterBuilder()
 874                 .parseCaseInsensitive()
 875                 .append(ISO_LOCAL_TIME)
 876                 .appendOffsetId()
 877                 .toFormatter(ResolverStyle.STRICT, null);
 878     }
 879 
 880     //-----------------------------------------------------------------------
 881     /**
 882      * The ISO time formatter that formats or parses a time, with the
 883      * offset if available, such as '10:15', '10:15:30' or '10:15:30+01:00'.
 884      * <p>
 885      * This returns an immutable formatter capable of formatting and parsing
 886      * the ISO-8601 extended offset time format.
 887      * The format consists of:
 888      * <ul>
 889      * <li>The {@link #ISO_LOCAL_TIME}
 890      * <li>If the offset is not available then the format is complete.
 891      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
 892      *  they will be handled even though this is not part of the ISO-8601 standard.
 893      *  Parsing is case insensitive.
 894      * </ul>
 895      * <p>
 896      * As this formatter has an optional element, it may be necessary to parse using
 897      * {@link DateTimeFormatter#parseBest}.
 898      * <p>
 899      * The returned formatter has no override chronology or zone.
 900      * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 901      */
 902     public static final DateTimeFormatter ISO_TIME;
 903     static {
 904         ISO_TIME = new DateTimeFormatterBuilder()
 905                 .parseCaseInsensitive()
 906                 .append(ISO_LOCAL_TIME)
 907                 .optionalStart()
 908                 .appendOffsetId()
 909                 .toFormatter(ResolverStyle.STRICT, null);
 910     }
 911 
 912     //-----------------------------------------------------------------------
 913     /**
 914      * The ISO date-time formatter that formats or parses a date-time without
 915      * an offset, such as '2011-12-03T10:15:30'.
 916      * <p>
 917      * This returns an immutable formatter capable of formatting and parsing
 918      * the ISO-8601 extended offset date-time format.
 919      * The format consists of:
 920      * <ul>
 921      * <li>The {@link #ISO_LOCAL_DATE}
 922      * <li>The letter 'T'. Parsing is case insensitive.
 923      * <li>The {@link #ISO_LOCAL_TIME}
 924      * </ul>
 925      * <p>
 926      * The returned formatter has a chronology of ISO set to ensure dates in
 927      * other calendar systems are correctly converted.
 928      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 929      */
 930     public static final DateTimeFormatter ISO_LOCAL_DATE_TIME;
 931     static {
 932         ISO_LOCAL_DATE_TIME = new DateTimeFormatterBuilder()
 933                 .parseCaseInsensitive()
 934                 .append(ISO_LOCAL_DATE)
 935                 .appendLiteral('T')
 936                 .append(ISO_LOCAL_TIME)
 937                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
 938     }
 939 
 940     //-----------------------------------------------------------------------
 941     /**
 942      * The ISO date-time formatter that formats or parses a date-time with an
 943      * offset, such as '2011-12-03T10:15:30+01:00'.
 944      * <p>
 945      * This returns an immutable formatter capable of formatting and parsing
 946      * the ISO-8601 extended offset date-time format.
 947      * The format consists of:
 948      * <ul>
 949      * <li>The {@link #ISO_LOCAL_DATE_TIME}
 950      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
 951      *  they will be handled even though this is not part of the ISO-8601 standard.
 952      *  The offset parsing is lenient, which allows the minutes and seconds to be optional.
 953      *  Parsing is case insensitive.
 954      * </ul>
 955      * <p>
 956      * The returned formatter has a chronology of ISO set to ensure dates in
 957      * other calendar systems are correctly converted.
 958      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 959      */
 960     public static final DateTimeFormatter ISO_OFFSET_DATE_TIME;
 961     static {
 962         ISO_OFFSET_DATE_TIME = new DateTimeFormatterBuilder()
 963                 .parseCaseInsensitive()
 964                 .append(ISO_LOCAL_DATE_TIME)
 965                 .parseLenient()
 966                 .appendOffsetId()
 967                 .parseStrict()
 968                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
 969     }
 970 
 971     //-----------------------------------------------------------------------
 972     /**
 973      * The ISO-like date-time formatter that formats or parses a date-time with
 974      * offset and zone, such as '2011-12-03T10:15:30+01:00[Europe/Paris]'.
 975      * <p>
 976      * This returns an immutable formatter capable of formatting and parsing
 977      * a format that extends the ISO-8601 extended offset date-time format
 978      * to add the time-zone.
 979      * The section in square brackets is not part of the ISO-8601 standard.
 980      * The format consists of:
 981      * <ul>
 982      * <li>The {@link #ISO_OFFSET_DATE_TIME}
 983      * <li>If the zone ID is not available or is a {@code ZoneOffset} then the format is complete.
 984      * <li>An open square bracket '['.
 985      * <li>The {@link ZoneId#getId() zone ID}. This is not part of the ISO-8601 standard.
 986      *  Parsing is case sensitive.
 987      * <li>A close square bracket ']'.
 988      * </ul>
 989      * <p>
 990      * The returned formatter has a chronology of ISO set to ensure dates in
 991      * other calendar systems are correctly converted.
 992      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
 993      */
 994     public static final DateTimeFormatter ISO_ZONED_DATE_TIME;
 995     static {
 996         ISO_ZONED_DATE_TIME = new DateTimeFormatterBuilder()
 997                 .append(ISO_OFFSET_DATE_TIME)
 998                 .optionalStart()
 999                 .appendLiteral('[')
1000                 .parseCaseSensitive()
1001                 .appendZoneRegionId()
1002                 .appendLiteral(']')
1003                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1004     }
1005 
1006     //-----------------------------------------------------------------------
1007     /**
1008      * The ISO-like date-time formatter that formats or parses a date-time with
1009      * the offset and zone if available, such as '2011-12-03T10:15:30',
1010      * '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'.
1011      * <p>
1012      * This returns an immutable formatter capable of formatting and parsing
1013      * the ISO-8601 extended local or offset date-time format, as well as the
1014      * extended non-ISO form specifying the time-zone.
1015      * The format consists of:
1016      * <ul>
1017      * <li>The {@link #ISO_LOCAL_DATE_TIME}
1018      * <li>If the offset is not available to format or parse then the format is complete.
1019      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
1020      *  they will be handled even though this is not part of the ISO-8601 standard.
1021      * <li>If the zone ID is not available or is a {@code ZoneOffset} then the format is complete.
1022      * <li>An open square bracket '['.
1023      * <li>The {@link ZoneId#getId() zone ID}. This is not part of the ISO-8601 standard.
1024      *  Parsing is case sensitive.
1025      * <li>A close square bracket ']'.
1026      * </ul>
1027      * <p>
1028      * As this formatter has an optional element, it may be necessary to parse using
1029      * {@link DateTimeFormatter#parseBest}.
1030      * <p>
1031      * The returned formatter has a chronology of ISO set to ensure dates in
1032      * other calendar systems are correctly converted.
1033      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1034      */
1035     public static final DateTimeFormatter ISO_DATE_TIME;
1036     static {
1037         ISO_DATE_TIME = new DateTimeFormatterBuilder()
1038                 .append(ISO_LOCAL_DATE_TIME)
1039                 .optionalStart()
1040                 .appendOffsetId()
1041                 .optionalStart()
1042                 .appendLiteral('[')
1043                 .parseCaseSensitive()
1044                 .appendZoneRegionId()
1045                 .appendLiteral(']')
1046                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1047     }
1048 
1049     //-----------------------------------------------------------------------
1050     /**
1051      * The ISO date formatter that formats or parses the ordinal date
1052      * without an offset, such as '2012-337'.
1053      * <p>
1054      * This returns an immutable formatter capable of formatting and parsing
1055      * the ISO-8601 extended ordinal date format.
1056      * The format consists of:
1057      * <ul>
1058      * <li>Four digits or more for the {@link ChronoField#YEAR year}.
1059      * Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits.
1060      * Years outside that range will have a prefixed positive or negative symbol.
1061      * <li>A dash
1062      * <li>Three digits for the {@link ChronoField#DAY_OF_YEAR day-of-year}.
1063      *  This is pre-padded by zero to ensure three digits.
1064      * <li>If the offset is not available to format or parse then the format is complete.
1065      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
1066      *  they will be handled even though this is not part of the ISO-8601 standard.
1067      *  Parsing is case insensitive.
1068      * </ul>
1069      * <p>
1070      * As this formatter has an optional element, it may be necessary to parse using
1071      * {@link DateTimeFormatter#parseBest}.
1072      * <p>
1073      * The returned formatter has a chronology of ISO set to ensure dates in
1074      * other calendar systems are correctly converted.
1075      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1076      */
1077     public static final DateTimeFormatter ISO_ORDINAL_DATE;
1078     static {
1079         ISO_ORDINAL_DATE = new DateTimeFormatterBuilder()
1080                 .parseCaseInsensitive()
1081                 .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
1082                 .appendLiteral('-')
1083                 .appendValue(DAY_OF_YEAR, 3)
1084                 .optionalStart()
1085                 .appendOffsetId()
1086                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1087     }
1088 
1089     //-----------------------------------------------------------------------
1090     /**
1091      * The ISO date formatter that formats or parses the week-based date
1092      * without an offset, such as '2012-W48-6'.
1093      * <p>
1094      * This returns an immutable formatter capable of formatting and parsing
1095      * the ISO-8601 extended week-based date format.
1096      * The format consists of:
1097      * <ul>
1098      * <li>Four digits or more for the {@link IsoFields#WEEK_BASED_YEAR week-based-year}.
1099      * Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits.
1100      * Years outside that range will have a prefixed positive or negative symbol.
1101      * <li>A dash
1102      * <li>The letter 'W'. Parsing is case insensitive.
1103      * <li>Two digits for the {@link IsoFields#WEEK_OF_WEEK_BASED_YEAR week-of-week-based-year}.
1104      *  This is pre-padded by zero to ensure three digits.
1105      * <li>A dash
1106      * <li>One digit for the {@link ChronoField#DAY_OF_WEEK day-of-week}.
1107      *  The value run from Monday (1) to Sunday (7).
1108      * <li>If the offset is not available to format or parse then the format is complete.
1109      * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
1110      *  they will be handled even though this is not part of the ISO-8601 standard.
1111      *  Parsing is case insensitive.
1112      * </ul>
1113      * <p>
1114      * As this formatter has an optional element, it may be necessary to parse using
1115      * {@link DateTimeFormatter#parseBest}.
1116      * <p>
1117      * The returned formatter has a chronology of ISO set to ensure dates in
1118      * other calendar systems are correctly converted.
1119      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1120      */
1121     public static final DateTimeFormatter ISO_WEEK_DATE;
1122     static {
1123         ISO_WEEK_DATE = new DateTimeFormatterBuilder()
1124                 .parseCaseInsensitive()
1125                 .appendValue(IsoFields.WEEK_BASED_YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
1126                 .appendLiteral("-W")
1127                 .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2)
1128                 .appendLiteral('-')
1129                 .appendValue(DAY_OF_WEEK, 1)
1130                 .optionalStart()
1131                 .appendOffsetId()
1132                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1133     }
1134 
1135     //-----------------------------------------------------------------------
1136     /**
1137      * The ISO instant formatter that formats or parses an instant in UTC,
1138      * such as '2011-12-03T10:15:30Z'.
1139      * <p>
1140      * This returns an immutable formatter capable of formatting and parsing
1141      * the ISO-8601 instant format.
1142      * When formatting, the instant will always be suffixed by 'Z' to indicate UTC.
1143      * The second-of-minute is always output.
1144      * The nano-of-second outputs zero, three, six or nine digits as necessary.
1145      * When parsing, the behaviour of {@link DateTimeFormatterBuilder#appendOffsetId()}
1146      * will be used to parse the offset, converting the instant to UTC as necessary.
1147      * The time to at least the seconds field is required.
1148      * Fractional seconds from zero to nine are parsed.
1149      * The localized decimal style is not used.
1150      * <p>
1151      * This is a special case formatter intended to allow a human readable form
1152      * of an {@link java.time.Instant}. The {@code Instant} class is designed to
1153      * only represent a point in time and internally stores a value in nanoseconds
1154      * from a fixed epoch of 1970-01-01Z. As such, an {@code Instant} cannot be
1155      * formatted as a date or time without providing some form of time-zone.
1156      * This formatter allows the {@code Instant} to be formatted, by providing
1157      * a suitable conversion using {@code ZoneOffset.UTC}.
1158      * <p>
1159      * The format consists of:
1160      * <ul>
1161      * <li>The {@link #ISO_OFFSET_DATE_TIME} where the instant is converted from
1162      *  {@link ChronoField#INSTANT_SECONDS} and {@link ChronoField#NANO_OF_SECOND}
1163      *  using the {@code UTC} offset. Parsing is case insensitive.
1164      * </ul>
1165      * <p>
1166      * The returned formatter has no override chronology or zone.
1167      * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1168      */
1169     public static final DateTimeFormatter ISO_INSTANT;
1170     static {
1171         ISO_INSTANT = new DateTimeFormatterBuilder()
1172                 .parseCaseInsensitive()
1173                 .appendInstant()
1174                 .toFormatter(ResolverStyle.STRICT, null);
1175     }
1176 
1177     //-----------------------------------------------------------------------
1178     /**
1179      * The ISO date formatter that formats or parses a date without an
1180      * offset, such as '20111203'.
1181      * <p>
1182      * This returns an immutable formatter capable of formatting and parsing
1183      * the ISO-8601 basic local date format.
1184      * The format consists of:
1185      * <ul>
1186      * <li>Four digits for the {@link ChronoField#YEAR year}.
1187      *  Only years in the range 0000 to 9999 are supported.
1188      * <li>Two digits for the {@link ChronoField#MONTH_OF_YEAR month-of-year}.
1189      *  This is pre-padded by zero to ensure two digits.
1190      * <li>Two digits for the {@link ChronoField#DAY_OF_MONTH day-of-month}.
1191      *  This is pre-padded by zero to ensure two digits.
1192      * <li>If the offset is not available to format or parse then the format is complete.
1193      * <li>The {@link ZoneOffset#getId() offset ID} without colons. If the offset has
1194      *  seconds then they will be handled even though this is not part of the ISO-8601 standard.
1195      *  The offset parsing is lenient, which allows the minutes and seconds to be optional.
1196      *  Parsing is case insensitive.
1197      * </ul>
1198      * <p>
1199      * As this formatter has an optional element, it may be necessary to parse using
1200      * {@link DateTimeFormatter#parseBest}.
1201      * <p>
1202      * The returned formatter has a chronology of ISO set to ensure dates in
1203      * other calendar systems are correctly converted.
1204      * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
1205      */
1206     public static final DateTimeFormatter BASIC_ISO_DATE;
1207     static {
1208         BASIC_ISO_DATE = new DateTimeFormatterBuilder()
1209                 .parseCaseInsensitive()
1210                 .appendValue(YEAR, 4)
1211                 .appendValue(MONTH_OF_YEAR, 2)
1212                 .appendValue(DAY_OF_MONTH, 2)
1213                 .optionalStart()
1214                 .parseLenient()
1215                 .appendOffset("+HHMMss", "Z")
1216                 .parseStrict()
1217                 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
1218     }
1219 
1220     //-----------------------------------------------------------------------
1221     /**
1222      * The RFC-1123 date-time formatter, such as 'Tue, 3 Jun 2008 11:05:30 GMT'.
1223      * <p>
1224      * This returns an immutable formatter capable of formatting and parsing
1225      * most of the RFC-1123 format.
1226      * RFC-1123 updates RFC-822 changing the year from two digits to four.
1227      * This implementation requires a four digit year.
1228      * This implementation also does not handle North American or military zone
1229      * names, only 'GMT' and offset amounts.
1230      * <p>
1231      * The format consists of:
1232      * <ul>
1233      * <li>If the day-of-week is not available to format or parse then jump to day-of-month.
1234      * <li>Three letter {@link ChronoField#DAY_OF_WEEK day-of-week} in English.
1235      * <li>A comma
1236      * <li>A space
1237      * <li>One or two digits for the {@link ChronoField#DAY_OF_MONTH day-of-month}.
1238      * <li>A space
1239      * <li>Three letter {@link ChronoField#MONTH_OF_YEAR month-of-year} in English.
1240      * <li>A space
1241      * <li>Four digits for the {@link ChronoField#YEAR year}.
1242      *  Only years in the range 0000 to 9999 are supported.
1243      * <li>A space
1244      * <li>Two digits for the {@link ChronoField#HOUR_OF_DAY hour-of-day}.
1245      *  This is pre-padded by zero to ensure two digits.
1246      * <li>A colon
1247      * <li>Two digits for the {@link ChronoField#MINUTE_OF_HOUR minute-of-hour}.
1248      *  This is pre-padded by zero to ensure two digits.
1249      * <li>If the second-of-minute is not available then jump to the next space.
1250      * <li>A colon
1251      * <li>Two digits for the {@link ChronoField#SECOND_OF_MINUTE second-of-minute}.
1252      *  This is pre-padded by zero to ensure two digits.
1253      * <li>A space
1254      * <li>The {@link ZoneOffset#getId() offset ID} without colons or seconds.
1255      *  An offset of zero uses "GMT". North American zone names and military zone names are not handled.
1256      * </ul>
1257      * <p>
1258      * Parsing is case insensitive.
1259      * <p>
1260      * The returned formatter has a chronology of ISO set to ensure dates in
1261      * other calendar systems are correctly converted.
1262      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
1263      */
1264     public static final DateTimeFormatter RFC_1123_DATE_TIME;
1265     static {
1266         // manually code maps to ensure correct data always used
1267         // (locale data can be changed by application code)
1268         Map<Long, String> dow = new HashMap<>();
1269         dow.put(1L, "Mon");
1270         dow.put(2L, "Tue");
1271         dow.put(3L, "Wed");
1272         dow.put(4L, "Thu");
1273         dow.put(5L, "Fri");
1274         dow.put(6L, "Sat");
1275         dow.put(7L, "Sun");
1276         Map<Long, String> moy = new HashMap<>();
1277         moy.put(1L, "Jan");
1278         moy.put(2L, "Feb");
1279         moy.put(3L, "Mar");
1280         moy.put(4L, "Apr");
1281         moy.put(5L, "May");
1282         moy.put(6L, "Jun");
1283         moy.put(7L, "Jul");
1284         moy.put(8L, "Aug");
1285         moy.put(9L, "Sep");
1286         moy.put(10L, "Oct");
1287         moy.put(11L, "Nov");
1288         moy.put(12L, "Dec");
1289         RFC_1123_DATE_TIME = new DateTimeFormatterBuilder()
1290                 .parseCaseInsensitive()
1291                 .parseLenient()
1292                 .optionalStart()
1293                 .appendText(DAY_OF_WEEK, dow)
1294                 .appendLiteral(", ")
1295                 .optionalEnd()
1296                 .appendValue(DAY_OF_MONTH, 1, 2, SignStyle.NOT_NEGATIVE)
1297                 .appendLiteral(' ')
1298                 .appendText(MONTH_OF_YEAR, moy)
1299                 .appendLiteral(' ')
1300                 .appendValue(YEAR, 4)  // 2 digit year not handled
1301                 .appendLiteral(' ')
1302                 .appendValue(HOUR_OF_DAY, 2)
1303                 .appendLiteral(':')
1304                 .appendValue(MINUTE_OF_HOUR, 2)
1305                 .optionalStart()
1306                 .appendLiteral(':')
1307                 .appendValue(SECOND_OF_MINUTE, 2)
1308                 .optionalEnd()
1309                 .appendLiteral(' ')
1310                 .appendOffset("+HHMM", "GMT")  // should handle UT/Z/EST/EDT/CST/CDT/MST/MDT/PST/MDT
1311                 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE);
1312     }
1313 
1314     //-----------------------------------------------------------------------
1315     /**
1316      * A query that provides access to the excess days that were parsed.
1317      * <p>
1318      * This returns a singleton {@linkplain TemporalQuery query} that provides
1319      * access to additional information from the parse. The query always returns
1320      * a non-null period, with a zero period returned instead of null.
1321      * <p>
1322      * There are two situations where this query may return a non-zero period.
1323      * <ul>
1324      * <li>If the {@code ResolverStyle} is {@code LENIENT} and a time is parsed
1325      *  without a date, then the complete result of the parse consists of a
1326      *  {@code LocalTime} and an excess {@code Period} in days.
1327      *
1328      * <li>If the {@code ResolverStyle} is {@code SMART} and a time is parsed
1329      *  without a date where the time is 24:00:00, then the complete result of
1330      *  the parse consists of a {@code LocalTime} of 00:00:00 and an excess
1331      *  {@code Period} of one day.
1332      * </ul>
1333      * <p>
1334      * In both cases, if a complete {@code ChronoLocalDateTime} or {@code Instant}
1335      * is parsed, then the excess days are added to the date part.
1336      * As a result, this query will return a zero period.
1337      * <p>
1338      * The {@code SMART} behaviour handles the common "end of day" 24:00 value.
1339      * Processing in {@code LENIENT} mode also produces the same result:
1340      * <pre>
1341      *  Text to parse        Parsed object                         Excess days
1342      *  "2012-12-03T00:00"   LocalDateTime.of(2012, 12, 3, 0, 0)   ZERO
1343      *  "2012-12-03T24:00"   LocalDateTime.of(2012, 12, 4, 0, 0)   ZERO
1344      *  "00:00"              LocalTime.of(0, 0)                    ZERO
1345      *  "24:00"              LocalTime.of(0, 0)                    Period.ofDays(1)
1346      * </pre>
1347      * The query can be used as follows:
1348      * <pre>
1349      *  TemporalAccessor parsed = formatter.parse(str);
1350      *  LocalTime time = parsed.query(LocalTime::from);
1351      *  Period extraDays = parsed.query(DateTimeFormatter.parsedExcessDays());
1352      * </pre>
1353      * @return a query that provides access to the excess days that were parsed
1354      */
1355     public static final TemporalQuery<Period> parsedExcessDays() {
1356         return PARSED_EXCESS_DAYS;
1357     }
1358     private static final TemporalQuery<Period> PARSED_EXCESS_DAYS = t -> {
1359         if (t instanceof Parsed) {
1360             return ((Parsed) t).excessDays;
1361         } else {
1362             return Period.ZERO;
1363         }
1364     };
1365 
1366     /**
1367      * A query that provides access to whether a leap-second was parsed.
1368      * <p>
1369      * This returns a singleton {@linkplain TemporalQuery query} that provides
1370      * access to additional information from the parse. The query always returns
1371      * a non-null boolean, true if parsing saw a leap-second, false if not.
1372      * <p>
1373      * Instant parsing handles the special "leap second" time of '23:59:60'.
1374      * Leap seconds occur at '23:59:60' in the UTC time-zone, but at other
1375      * local times in different time-zones. To avoid this potential ambiguity,
1376      * the handling of leap-seconds is limited to
1377      * {@link DateTimeFormatterBuilder#appendInstant()}, as that method
1378      * always parses the instant with the UTC zone offset.
1379      * <p>
1380      * If the time '23:59:60' is received, then a simple conversion is applied,
1381      * replacing the second-of-minute of 60 with 59. This query can be used
1382      * on the parse result to determine if the leap-second adjustment was made.
1383      * The query will return {@code true} if it did adjust to remove the
1384      * leap-second, and {@code false} if not. Note that applying a leap-second
1385      * smoothing mechanism, such as UTC-SLS, is the responsibility of the
1386      * application, as follows:
1387      * <pre>
1388      *  TemporalAccessor parsed = formatter.parse(str);
1389      *  Instant instant = parsed.query(Instant::from);
1390      *  if (parsed.query(DateTimeFormatter.parsedLeapSecond())) {
1391      *    // validate leap-second is correct and apply correct smoothing
1392      *  }
1393      * </pre>
1394      * @return a query that provides access to whether a leap-second was parsed
1395      */
1396     public static final TemporalQuery<Boolean> parsedLeapSecond() {
1397         return PARSED_LEAP_SECOND;
1398     }
1399     private static final TemporalQuery<Boolean> PARSED_LEAP_SECOND = t -> {
1400         if (t instanceof Parsed) {
1401             return ((Parsed) t).leapSecond;
1402         } else {
1403             return Boolean.FALSE;
1404         }
1405     };
1406 
1407     //-----------------------------------------------------------------------
1408     /**
1409      * Constructor.
1410      *
1411      * @param printerParser  the printer/parser to use, not null
1412      * @param locale  the locale to use, not null
1413      * @param decimalStyle  the DecimalStyle to use, not null
1414      * @param resolverStyle  the resolver style to use, not null
1415      * @param resolverFields  the fields to use during resolving, null for all fields
1416      * @param chrono  the chronology to use, null for no override
1417      * @param zone  the zone to use, null for no override
1418      */
1419     DateTimeFormatter(CompositePrinterParser printerParser,
1420             Locale locale, DecimalStyle decimalStyle,
1421             ResolverStyle resolverStyle, Set<TemporalField> resolverFields,
1422             Chronology chrono, ZoneId zone) {
1423         this.printerParser = Objects.requireNonNull(printerParser, "printerParser");
1424         this.resolverFields = resolverFields;
1425         this.locale = Objects.requireNonNull(locale, "locale");
1426         this.decimalStyle = Objects.requireNonNull(decimalStyle, "decimalStyle");
1427         this.resolverStyle = Objects.requireNonNull(resolverStyle, "resolverStyle");
1428         this.chrono = chrono;
1429         this.zone = zone;
1430     }
1431 
1432     //-----------------------------------------------------------------------
1433     /**
1434      * Gets the locale to be used during formatting.
1435      * <p>
1436      * This is used to lookup any part of the formatter needing specific
1437      * localization, such as the text or localized pattern.
1438      *
1439      * @return the locale of this formatter, not null
1440      */
1441     public Locale getLocale() {
1442         return locale;
1443     }
1444 
1445     /**
1446      * Returns a copy of this formatter with a new locale.
1447      * <p>
1448      * This is used to lookup any part of the formatter needing specific
1449      * localization, such as the text or localized pattern.
1450      * <p>
1451      * The locale is stored as passed in, without further processing.
1452      * If the locale has <a href="../../util/Locale.html#def_locale_extension">
1453      * Unicode extensions</a>, they may be used later in text
1454      * processing. To set the chronology, time-zone and decimal style from
1455      * unicode extensions, see {@link #localizedBy localizedBy()}.
1456      * <p>
1457      * This instance is immutable and unaffected by this method call.
1458      *
1459      * @param locale  the new locale, not null
1460      * @return a formatter based on this formatter with the requested locale, not null
1461      * @see #localizedBy(Locale)
1462      */
1463     public DateTimeFormatter withLocale(Locale locale) {
1464         if (this.locale.equals(locale)) {
1465             return this;
1466         }
1467         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1468     }
1469 
1470     /**
1471      * Returns a copy of this formatter with localized values of the locale,
1472      * calendar, region, decimal style and/or timezone, that supercede values in
1473      * this formatter.
1474      * <p>
1475      * This is used to lookup any part of the formatter needing specific
1476      * localization, such as the text or localized pattern. If the locale contains the
1477      * "ca" (calendar), "nu" (numbering system), "rg" (region override), and/or
1478      * "tz" (timezone)
1479      * <a href="../../util/Locale.html#def_locale_extension">Unicode extensions</a>,
1480      * the chronology, numbering system and/or the zone are overridden. If both "ca"
1481      * and "rg" are specified, the chronology from the "ca" extension supersedes the
1482      * implicit one from the "rg" extension. Same is true for the "nu" extension.
1483      * <p>
1484      * Unlike the {@link #withLocale withLocale} method, the call to this method may
1485      * produce a different formatter depending on the order of method chaining with
1486      * other withXXXX() methods.
1487      * <p>
1488      * This instance is immutable and unaffected by this method call.
1489      *
1490      * @param locale  the locale, not null
1491      * @return a formatter based on this formatter with localized values of
1492      *      the calendar, decimal style and/or timezone, that supercede values in this
1493      *      formatter.
1494      * @see #withLocale(Locale)
1495      * @since 10
1496      */
1497     public DateTimeFormatter localizedBy(Locale locale) {
1498         if (this.locale.equals(locale)) {
1499             return this;
1500         }
1501 
1502         // Check for decimalStyle/chronology/timezone in locale object
1503         Chronology c = locale.getUnicodeLocaleType("ca") != null ?
1504                        Chronology.ofLocale(locale) : chrono;
1505         DecimalStyle ds = locale.getUnicodeLocaleType("nu") != null ?
1506                        DecimalStyle.of(locale) : decimalStyle;
1507         String tzType = locale.getUnicodeLocaleType("tz");
1508         ZoneId z  = tzType != null ?
1509                     TimeZoneNameUtility.convertLDMLShortID(tzType)
1510                         .map(ZoneId::of)
1511                         .orElse(zone) :
1512                     zone;
1513         return new DateTimeFormatter(printerParser, locale, ds, resolverStyle, resolverFields, c, z);
1514     }
1515 
1516     //-----------------------------------------------------------------------
1517     /**
1518      * Gets the DecimalStyle to be used during formatting.
1519      *
1520      * @return the locale of this formatter, not null
1521      */
1522     public DecimalStyle getDecimalStyle() {
1523         return decimalStyle;
1524     }
1525 
1526     /**
1527      * Returns a copy of this formatter with a new DecimalStyle.
1528      * <p>
1529      * This instance is immutable and unaffected by this method call.
1530      *
1531      * @param decimalStyle  the new DecimalStyle, not null
1532      * @return a formatter based on this formatter with the requested DecimalStyle, not null
1533      */
1534     public DateTimeFormatter withDecimalStyle(DecimalStyle decimalStyle) {
1535         if (this.decimalStyle.equals(decimalStyle)) {
1536             return this;
1537         }
1538         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1539     }
1540 
1541     //-----------------------------------------------------------------------
1542     /**
1543      * Gets the overriding chronology to be used during formatting.
1544      * <p>
1545      * This returns the override chronology, used to convert dates.
1546      * By default, a formatter has no override chronology, returning null.
1547      * See {@link #withChronology(Chronology)} for more details on overriding.
1548      *
1549      * @return the override chronology of this formatter, null if no override
1550      */
1551     public Chronology getChronology() {
1552         return chrono;
1553     }
1554 
1555     /**
1556      * Returns a copy of this formatter with a new override chronology.
1557      * <p>
1558      * This returns a formatter with similar state to this formatter but
1559      * with the override chronology set.
1560      * By default, a formatter has no override chronology, returning null.
1561      * <p>
1562      * If an override is added, then any date that is formatted or parsed will be affected.
1563      * <p>
1564      * When formatting, if the temporal object contains a date, then it will
1565      * be converted to a date in the override chronology.
1566      * Whether the temporal contains a date is determined by querying the
1567      * {@link ChronoField#EPOCH_DAY EPOCH_DAY} field.
1568      * Any time or zone will be retained unaltered unless overridden.
1569      * <p>
1570      * If the temporal object does not contain a date, but does contain one
1571      * or more {@code ChronoField} date fields, then a {@code DateTimeException}
1572      * is thrown. In all other cases, the override chronology is added to the temporal,
1573      * replacing any previous chronology, but without changing the date/time.
1574      * <p>
1575      * When parsing, there are two distinct cases to consider.
1576      * If a chronology has been parsed directly from the text, perhaps because
1577      * {@link DateTimeFormatterBuilder#appendChronologyId()} was used, then
1578      * this override chronology has no effect.
1579      * If no zone has been parsed, then this override chronology will be used
1580      * to interpret the {@code ChronoField} values into a date according to the
1581      * date resolving rules of the chronology.
1582      * <p>
1583      * This instance is immutable and unaffected by this method call.
1584      *
1585      * @param chrono  the new chronology, null if no override
1586      * @return a formatter based on this formatter with the requested override chronology, not null
1587      */
1588     public DateTimeFormatter withChronology(Chronology chrono) {
1589         if (Objects.equals(this.chrono, chrono)) {
1590             return this;
1591         }
1592         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1593     }
1594 
1595     //-----------------------------------------------------------------------
1596     /**
1597      * Gets the overriding zone to be used during formatting.
1598      * <p>
1599      * This returns the override zone, used to convert instants.
1600      * By default, a formatter has no override zone, returning null.
1601      * See {@link #withZone(ZoneId)} for more details on overriding.
1602      *
1603      * @return the override zone of this formatter, null if no override
1604      */
1605     public ZoneId getZone() {
1606         return zone;
1607     }
1608 
1609     /**
1610      * Returns a copy of this formatter with a new override zone.
1611      * <p>
1612      * This returns a formatter with similar state to this formatter but
1613      * with the override zone set.
1614      * By default, a formatter has no override zone, returning null.
1615      * <p>
1616      * If an override is added, then any instant that is formatted or parsed will be affected.
1617      * <p>
1618      * When formatting, if the temporal object contains an instant, then it will
1619      * be converted to a zoned date-time using the override zone.
1620      * Whether the temporal is an instant is determined by querying the
1621      * {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS} field.
1622      * If the input has a chronology then it will be retained unless overridden.
1623      * If the input does not have a chronology, such as {@code Instant}, then
1624      * the ISO chronology will be used.
1625      * <p>
1626      * If the temporal object does not contain an instant, but does contain
1627      * an offset then an additional check is made. If the normalized override
1628      * zone is an offset that differs from the offset of the temporal, then
1629      * a {@code DateTimeException} is thrown. In all other cases, the override
1630      * zone is added to the temporal, replacing any previous zone, but without
1631      * changing the date/time.
1632      * <p>
1633      * When parsing, there are two distinct cases to consider.
1634      * If a zone has been parsed directly from the text, perhaps because
1635      * {@link DateTimeFormatterBuilder#appendZoneId()} was used, then
1636      * this override zone has no effect.
1637      * If no zone has been parsed, then this override zone will be included in
1638      * the result of the parse where it can be used to build instants and date-times.
1639      * <p>
1640      * This instance is immutable and unaffected by this method call.
1641      *
1642      * @param zone  the new override zone, null if no override
1643      * @return a formatter based on this formatter with the requested override zone, not null
1644      */
1645     public DateTimeFormatter withZone(ZoneId zone) {
1646         if (Objects.equals(this.zone, zone)) {
1647             return this;
1648         }
1649         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1650     }
1651 
1652     //-----------------------------------------------------------------------
1653     /**
1654      * Gets the resolver style to use during parsing.
1655      * <p>
1656      * This returns the resolver style, used during the second phase of parsing
1657      * when fields are resolved into dates and times.
1658      * By default, a formatter has the {@link ResolverStyle#SMART SMART} resolver style.
1659      * See {@link #withResolverStyle(ResolverStyle)} for more details.
1660      *
1661      * @return the resolver style of this formatter, not null
1662      */
1663     public ResolverStyle getResolverStyle() {
1664         return resolverStyle;
1665     }
1666 
1667     /**
1668      * Returns a copy of this formatter with a new resolver style.
1669      * <p>
1670      * This returns a formatter with similar state to this formatter but
1671      * with the resolver style set. By default, a formatter has the
1672      * {@link ResolverStyle#SMART SMART} resolver style.
1673      * <p>
1674      * Changing the resolver style only has an effect during parsing.
1675      * Parsing a text string occurs in two phases.
1676      * Phase 1 is a basic text parse according to the fields added to the builder.
1677      * Phase 2 resolves the parsed field-value pairs into date and/or time objects.
1678      * The resolver style is used to control how phase 2, resolving, happens.
1679      * See {@code ResolverStyle} for more information on the options available.
1680      * <p>
1681      * This instance is immutable and unaffected by this method call.
1682      *
1683      * @param resolverStyle  the new resolver style, not null
1684      * @return a formatter based on this formatter with the requested resolver style, not null
1685      */
1686     public DateTimeFormatter withResolverStyle(ResolverStyle resolverStyle) {
1687         Objects.requireNonNull(resolverStyle, "resolverStyle");
1688         if (Objects.equals(this.resolverStyle, resolverStyle)) {
1689             return this;
1690         }
1691         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1692     }
1693 
1694     //-----------------------------------------------------------------------
1695     /**
1696      * Gets the resolver fields to use during parsing.
1697      * <p>
1698      * This returns the resolver fields, used during the second phase of parsing
1699      * when fields are resolved into dates and times.
1700      * By default, a formatter has no resolver fields, and thus returns null.
1701      * See {@link #withResolverFields(Set)} for more details.
1702      *
1703      * @return the immutable set of resolver fields of this formatter, null if no fields
1704      */
1705     public Set<TemporalField> getResolverFields() {
1706         return resolverFields;
1707     }
1708 
1709     /**
1710      * Returns a copy of this formatter with a new set of resolver fields.
1711      * <p>
1712      * This returns a formatter with similar state to this formatter but with
1713      * the resolver fields set. By default, a formatter has no resolver fields.
1714      * <p>
1715      * Changing the resolver fields only has an effect during parsing.
1716      * Parsing a text string occurs in two phases.
1717      * Phase 1 is a basic text parse according to the fields added to the builder.
1718      * Phase 2 resolves the parsed field-value pairs into date and/or time objects.
1719      * The resolver fields are used to filter the field-value pairs between phase 1 and 2.
1720      * <p>
1721      * This can be used to select between two or more ways that a date or time might
1722      * be resolved. For example, if the formatter consists of year, month, day-of-month
1723      * and day-of-year, then there are two ways to resolve a date.
1724      * Calling this method with the arguments {@link ChronoField#YEAR YEAR} and
1725      * {@link ChronoField#DAY_OF_YEAR DAY_OF_YEAR} will ensure that the date is
1726      * resolved using the year and day-of-year, effectively meaning that the month
1727      * and day-of-month are ignored during the resolving phase.
1728      * <p>
1729      * In a similar manner, this method can be used to ignore secondary fields that
1730      * would otherwise be cross-checked. For example, if the formatter consists of year,
1731      * month, day-of-month and day-of-week, then there is only one way to resolve a
1732      * date, but the parsed value for day-of-week will be cross-checked against the
1733      * resolved date. Calling this method with the arguments {@link ChronoField#YEAR YEAR},
1734      * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and
1735      * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} will ensure that the date is
1736      * resolved correctly, but without any cross-check for the day-of-week.
1737      * <p>
1738      * In implementation terms, this method behaves as follows. The result of the
1739      * parsing phase can be considered to be a map of field to value. The behavior
1740      * of this method is to cause that map to be filtered between phase 1 and 2,
1741      * removing all fields other than those specified as arguments to this method.
1742      * <p>
1743      * This instance is immutable and unaffected by this method call.
1744      *
1745      * @param resolverFields  the new set of resolver fields, null if no fields
1746      * @return a formatter based on this formatter with the requested resolver style, not null
1747      */
1748     public DateTimeFormatter withResolverFields(TemporalField... resolverFields) {
1749         Set<TemporalField> fields = null;
1750         if (resolverFields != null) {
1751             // Set.of cannot be used because it is hostile to nulls and duplicate elements
1752             fields = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(resolverFields)));
1753         }
1754         if (Objects.equals(this.resolverFields, fields)) {
1755             return this;
1756         }
1757         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, fields, chrono, zone);
1758     }
1759 
1760     /**
1761      * Returns a copy of this formatter with a new set of resolver fields.
1762      * <p>
1763      * This returns a formatter with similar state to this formatter but with
1764      * the resolver fields set. By default, a formatter has no resolver fields.
1765      * <p>
1766      * Changing the resolver fields only has an effect during parsing.
1767      * Parsing a text string occurs in two phases.
1768      * Phase 1 is a basic text parse according to the fields added to the builder.
1769      * Phase 2 resolves the parsed field-value pairs into date and/or time objects.
1770      * The resolver fields are used to filter the field-value pairs between phase 1 and 2.
1771      * <p>
1772      * This can be used to select between two or more ways that a date or time might
1773      * be resolved. For example, if the formatter consists of year, month, day-of-month
1774      * and day-of-year, then there are two ways to resolve a date.
1775      * Calling this method with the arguments {@link ChronoField#YEAR YEAR} and
1776      * {@link ChronoField#DAY_OF_YEAR DAY_OF_YEAR} will ensure that the date is
1777      * resolved using the year and day-of-year, effectively meaning that the month
1778      * and day-of-month are ignored during the resolving phase.
1779      * <p>
1780      * In a similar manner, this method can be used to ignore secondary fields that
1781      * would otherwise be cross-checked. For example, if the formatter consists of year,
1782      * month, day-of-month and day-of-week, then there is only one way to resolve a
1783      * date, but the parsed value for day-of-week will be cross-checked against the
1784      * resolved date. Calling this method with the arguments {@link ChronoField#YEAR YEAR},
1785      * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and
1786      * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} will ensure that the date is
1787      * resolved correctly, but without any cross-check for the day-of-week.
1788      * <p>
1789      * In implementation terms, this method behaves as follows. The result of the
1790      * parsing phase can be considered to be a map of field to value. The behavior
1791      * of this method is to cause that map to be filtered between phase 1 and 2,
1792      * removing all fields other than those specified as arguments to this method.
1793      * <p>
1794      * This instance is immutable and unaffected by this method call.
1795      *
1796      * @param resolverFields  the new set of resolver fields, null if no fields
1797      * @return a formatter based on this formatter with the requested resolver style, not null
1798      */
1799     public DateTimeFormatter withResolverFields(Set<TemporalField> resolverFields) {
1800         if (Objects.equals(this.resolverFields, resolverFields)) {
1801             return this;
1802         }
1803         if (resolverFields != null) {
1804             resolverFields = Collections.unmodifiableSet(new HashSet<>(resolverFields));
1805         }
1806         return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
1807     }
1808 
1809     //-----------------------------------------------------------------------
1810     /**
1811      * Formats a date-time object using this formatter.
1812      * <p>
1813      * This formats the date-time to a String using the rules of the formatter.
1814      *
1815      * @param temporal  the temporal object to format, not null
1816      * @return the formatted string, not null
1817      * @throws DateTimeException if an error occurs during formatting
1818      */
1819     public String format(TemporalAccessor temporal) {
1820         StringBuilder buf = new StringBuilder(32);
1821         formatTo(temporal, buf);
1822         return buf.toString();
1823     }
1824 
1825     //-----------------------------------------------------------------------
1826     /**
1827      * Formats a date-time object to an {@code Appendable} using this formatter.
1828      * <p>
1829      * This outputs the formatted date-time to the specified destination.
1830      * {@link Appendable} is a general purpose interface that is implemented by all
1831      * key character output classes including {@code StringBuffer}, {@code StringBuilder},
1832      * {@code PrintStream} and {@code Writer}.
1833      * <p>
1834      * Although {@code Appendable} methods throw an {@code IOException}, this method does not.
1835      * Instead, any {@code IOException} is wrapped in a runtime exception.
1836      *
1837      * @param temporal  the temporal object to format, not null
1838      * @param appendable  the appendable to format to, not null
1839      * @throws DateTimeException if an error occurs during formatting
1840      */
1841     public void formatTo(TemporalAccessor temporal, Appendable appendable) {
1842         Objects.requireNonNull(temporal, "temporal");
1843         Objects.requireNonNull(appendable, "appendable");
1844         try {
1845             DateTimePrintContext context = new DateTimePrintContext(temporal, this);
1846             if (appendable instanceof StringBuilder) {
1847                 printerParser.format(context, (StringBuilder) appendable);
1848             } else {
1849                 // buffer output to avoid writing to appendable in case of error
1850                 StringBuilder buf = new StringBuilder(32);
1851                 printerParser.format(context, buf);
1852                 appendable.append(buf);
1853             }
1854         } catch (IOException ex) {
1855             throw new DateTimeException(ex.getMessage(), ex);
1856         }
1857     }
1858 
1859     //-----------------------------------------------------------------------
1860     /**
1861      * Fully parses the text producing a temporal object.
1862      * <p>
1863      * This parses the entire text producing a temporal object.
1864      * It is typically more useful to use {@link #parse(CharSequence, TemporalQuery)}.
1865      * The result of this method is {@code TemporalAccessor} which has been resolved,
1866      * applying basic validation checks to help ensure a valid date-time.
1867      * <p>
1868      * If the parse completes without reading the entire length of the text,
1869      * or a problem occurs during parsing or merging, then an exception is thrown.
1870      *
1871      * @param text  the text to parse, not null
1872      * @return the parsed temporal object, not null
1873      * @throws DateTimeParseException if unable to parse the requested result
1874      */
1875     public TemporalAccessor parse(CharSequence text) {
1876         Objects.requireNonNull(text, "text");
1877         try {
1878             return parseResolved0(text, null);
1879         } catch (DateTimeParseException ex) {
1880             throw ex;
1881         } catch (RuntimeException ex) {
1882             throw createError(text, ex);
1883         }
1884     }
1885 
1886     /**
1887      * Parses the text using this formatter, providing control over the text position.
1888      * <p>
1889      * This parses the text without requiring the parse to start from the beginning
1890      * of the string or finish at the end.
1891      * The result of this method is {@code TemporalAccessor} which has been resolved,
1892      * applying basic validation checks to help ensure a valid date-time.
1893      * <p>
1894      * The text will be parsed from the specified start {@code ParsePosition}.
1895      * The entire length of the text does not have to be parsed, the {@code ParsePosition}
1896      * will be updated with the index at the end of parsing.
1897      * <p>
1898      * The operation of this method is slightly different to similar methods using
1899      * {@code ParsePosition} on {@code java.text.Format}. That class will return
1900      * errors using the error index on the {@code ParsePosition}. By contrast, this
1901      * method will throw a {@link DateTimeParseException} if an error occurs, with
1902      * the exception containing the error index.
1903      * This change in behavior is necessary due to the increased complexity of
1904      * parsing and resolving dates/times in this API.
1905      * <p>
1906      * If the formatter parses the same field more than once with different values,
1907      * the result will be an error.
1908      *
1909      * @param text  the text to parse, not null
1910      * @param position  the position to parse from, updated with length parsed
1911      *  and the index of any error, not null
1912      * @return the parsed temporal object, not null
1913      * @throws DateTimeParseException if unable to parse the requested result
1914      * @throws IndexOutOfBoundsException if the position is invalid
1915      */
1916     public TemporalAccessor parse(CharSequence text, ParsePosition position) {
1917         Objects.requireNonNull(text, "text");
1918         Objects.requireNonNull(position, "position");
1919         try {
1920             return parseResolved0(text, position);
1921         } catch (DateTimeParseException | IndexOutOfBoundsException ex) {
1922             throw ex;
1923         } catch (RuntimeException ex) {
1924             throw createError(text, ex);
1925         }
1926     }
1927 
1928     //-----------------------------------------------------------------------
1929     /**
1930      * Fully parses the text producing an object of the specified type.
1931      * <p>
1932      * Most applications should use this method for parsing.
1933      * It parses the entire text to produce the required date-time.
1934      * The query is typically a method reference to a {@code from(TemporalAccessor)} method.
1935      * For example:
1936      * <pre>
1937      *  LocalDateTime dt = parser.parse(str, LocalDateTime::from);
1938      * </pre>
1939      * If the parse completes without reading the entire length of the text,
1940      * or a problem occurs during parsing or merging, then an exception is thrown.
1941      *
1942      * @param <T> the type of the parsed date-time
1943      * @param text  the text to parse, not null
1944      * @param query  the query defining the type to parse to, not null
1945      * @return the parsed date-time, not null
1946      * @throws DateTimeParseException if unable to parse the requested result
1947      */
1948     public <T> T parse(CharSequence text, TemporalQuery<T> query) {
1949         Objects.requireNonNull(text, "text");
1950         Objects.requireNonNull(query, "query");
1951         try {
1952             return parseResolved0(text, null).query(query);
1953         } catch (DateTimeParseException ex) {
1954             throw ex;
1955         } catch (RuntimeException ex) {
1956             throw createError(text, ex);
1957         }
1958     }
1959 
1960     /**
1961      * Fully parses the text producing an object of one of the specified types.
1962      * <p>
1963      * This parse method is convenient for use when the parser can handle optional elements.
1964      * For example, a pattern of 'uuuu-MM-dd HH.mm[ VV]' can be fully parsed to a {@code ZonedDateTime},
1965      * or partially parsed to a {@code LocalDateTime}.
1966      * The queries must be specified in order, starting from the best matching full-parse option
1967      * and ending with the worst matching minimal parse option.
1968      * The query is typically a method reference to a {@code from(TemporalAccessor)} method.
1969      * <p>
1970      * The result is associated with the first type that successfully parses.
1971      * Normally, applications will use {@code instanceof} to check the result.
1972      * For example:
1973      * <pre>
1974      *  TemporalAccessor dt = parser.parseBest(str, ZonedDateTime::from, LocalDateTime::from);
1975      *  if (dt instanceof ZonedDateTime) {
1976      *   ...
1977      *  } else {
1978      *   ...
1979      *  }
1980      * </pre>
1981      * If the parse completes without reading the entire length of the text,
1982      * or a problem occurs during parsing or merging, then an exception is thrown.
1983      *
1984      * @param text  the text to parse, not null
1985      * @param queries  the queries defining the types to attempt to parse to,
1986      *  must implement {@code TemporalAccessor}, not null
1987      * @return the parsed date-time, not null
1988      * @throws IllegalArgumentException if less than 2 types are specified
1989      * @throws DateTimeParseException if unable to parse the requested result
1990      */
1991     public TemporalAccessor parseBest(CharSequence text, TemporalQuery<?>... queries) {
1992         Objects.requireNonNull(text, "text");
1993         Objects.requireNonNull(queries, "queries");
1994         if (queries.length < 2) {
1995             throw new IllegalArgumentException("At least two queries must be specified");
1996         }
1997         try {
1998             TemporalAccessor resolved = parseResolved0(text, null);
1999             for (TemporalQuery<?> query : queries) {
2000                 try {
2001                     return (TemporalAccessor) resolved.query(query);
2002                 } catch (RuntimeException ex) {
2003                     // continue
2004                 }
2005             }
2006             throw new DateTimeException("Unable to convert parsed text using any of the specified queries");
2007         } catch (DateTimeParseException ex) {
2008             throw ex;
2009         } catch (RuntimeException ex) {
2010             throw createError(text, ex);
2011         }
2012     }
2013 
2014     private DateTimeParseException createError(CharSequence text, RuntimeException ex) {
2015         String abbr;
2016         if (text.length() > 64) {
2017             abbr = text.subSequence(0, 64).toString() + "...";
2018         } else {
2019             abbr = text.toString();
2020         }
2021         return new DateTimeParseException("Text '" + abbr + "' could not be parsed: " + ex.getMessage(), text, 0, ex);
2022     }
2023 
2024     //-----------------------------------------------------------------------
2025     /**
2026      * Parses and resolves the specified text.
2027      * <p>
2028      * This parses to a {@code TemporalAccessor} ensuring that the text is fully parsed.
2029      *
2030      * @param text  the text to parse, not null
2031      * @param position  the position to parse from, updated with length parsed
2032      *  and the index of any error, null if parsing whole string
2033      * @return the resolved result of the parse, not null
2034      * @throws DateTimeParseException if the parse fails
2035      * @throws DateTimeException if an error occurs while resolving the date or time
2036      * @throws IndexOutOfBoundsException if the position is invalid
2037      */
2038     private TemporalAccessor parseResolved0(final CharSequence text, final ParsePosition position) {
2039         ParsePosition pos = (position != null ? position : new ParsePosition(0));
2040         DateTimeParseContext context = parseUnresolved0(text, pos);
2041         if (context == null || pos.getErrorIndex() >= 0 || (position == null && pos.getIndex() < text.length())) {
2042             String abbr;
2043             if (text.length() > 64) {
2044                 abbr = text.subSequence(0, 64).toString() + "...";
2045             } else {
2046                 abbr = text.toString();
2047             }
2048             if (pos.getErrorIndex() >= 0) {
2049                 throw new DateTimeParseException("Text '" + abbr + "' could not be parsed at index " +
2050                         pos.getErrorIndex(), text, pos.getErrorIndex());
2051             } else {
2052                 throw new DateTimeParseException("Text '" + abbr + "' could not be parsed, unparsed text found at index " +
2053                         pos.getIndex(), text, pos.getIndex());
2054             }
2055         }
2056         return context.toResolved(resolverStyle, resolverFields);
2057     }
2058 
2059     /**
2060      * Parses the text using this formatter, without resolving the result, intended
2061      * for advanced use cases.
2062      * <p>
2063      * Parsing is implemented as a two-phase operation.
2064      * First, the text is parsed using the layout defined by the formatter, producing
2065      * a {@code Map} of field to value, a {@code ZoneId} and a {@code Chronology}.
2066      * Second, the parsed data is <em>resolved</em>, by validating, combining and
2067      * simplifying the various fields into more useful ones.
2068      * This method performs the parsing stage but not the resolving stage.
2069      * <p>
2070      * The result of this method is {@code TemporalAccessor} which represents the
2071      * data as seen in the input. Values are not validated, thus parsing a date string
2072      * of '2012-00-65' would result in a temporal with three fields - year of '2012',
2073      * month of '0' and day-of-month of '65'.
2074      * <p>
2075      * The text will be parsed from the specified start {@code ParsePosition}.
2076      * The entire length of the text does not have to be parsed, the {@code ParsePosition}
2077      * will be updated with the index at the end of parsing.
2078      * <p>
2079      * Errors are returned using the error index field of the {@code ParsePosition}
2080      * instead of {@code DateTimeParseException}.
2081      * The returned error index will be set to an index indicative of the error.
2082      * Callers must check for errors before using the result.
2083      * <p>
2084      * If the formatter parses the same field more than once with different values,
2085      * the result will be an error.
2086      * <p>
2087      * This method is intended for advanced use cases that need access to the
2088      * internal state during parsing. Typical application code should use
2089      * {@link #parse(CharSequence, TemporalQuery)} or the parse method on the target type.
2090      *
2091      * @param text  the text to parse, not null
2092      * @param position  the position to parse from, updated with length parsed
2093      *  and the index of any error, not null
2094      * @return the parsed text, null if the parse results in an error
2095      * @throws DateTimeException if some problem occurs during parsing
2096      * @throws IndexOutOfBoundsException if the position is invalid
2097      */
2098     public TemporalAccessor parseUnresolved(CharSequence text, ParsePosition position) {
2099         DateTimeParseContext context = parseUnresolved0(text, position);
2100         if (context == null) {
2101             return null;
2102         }
2103         return context.toUnresolved();
2104     }
2105 
2106     private DateTimeParseContext parseUnresolved0(CharSequence text, ParsePosition position) {
2107         Objects.requireNonNull(text, "text");
2108         Objects.requireNonNull(position, "position");
2109         DateTimeParseContext context = new DateTimeParseContext(this);
2110         int pos = position.getIndex();
2111         pos = printerParser.parse(context, text, pos);
2112         if (pos < 0) {
2113             position.setErrorIndex(~pos);  // index not updated from input
2114             return null;
2115         }
2116         position.setIndex(pos);  // errorIndex not updated from input
2117         return context;
2118     }
2119 
2120     //-----------------------------------------------------------------------
2121     /**
2122      * Returns the formatter as a composite printer parser.
2123      *
2124      * @param optional  whether the printer/parser should be optional
2125      * @return the printer/parser, not null
2126      */
2127     CompositePrinterParser toPrinterParser(boolean optional) {
2128         return printerParser.withOptional(optional);
2129     }
2130 
2131     /**
2132      * Returns this formatter as a {@code java.text.Format} instance.
2133      * <p>
2134      * The returned {@link Format} instance will format any {@link TemporalAccessor}
2135      * and parses to a resolved {@link TemporalAccessor}.
2136      * <p>
2137      * Exceptions will follow the definitions of {@code Format}, see those methods
2138      * for details about {@code IllegalArgumentException} during formatting and
2139      * {@code ParseException} or null during parsing.
2140      * The format does not support attributing of the returned format string.
2141      *
2142      * @return this formatter as a classic format instance, not null
2143      */
2144     public Format toFormat() {
2145         return new ClassicFormat(this, null);
2146     }
2147 
2148     /**
2149      * Returns this formatter as a {@code java.text.Format} instance that will
2150      * parse using the specified query.
2151      * <p>
2152      * The returned {@link Format} instance will format any {@link TemporalAccessor}
2153      * and parses to the type specified.
2154      * The type must be one that is supported by {@link #parse}.
2155      * <p>
2156      * Exceptions will follow the definitions of {@code Format}, see those methods
2157      * for details about {@code IllegalArgumentException} during formatting and
2158      * {@code ParseException} or null during parsing.
2159      * The format does not support attributing of the returned format string.
2160      *
2161      * @param parseQuery  the query defining the type to parse to, not null
2162      * @return this formatter as a classic format instance, not null
2163      */
2164     public Format toFormat(TemporalQuery<?> parseQuery) {
2165         Objects.requireNonNull(parseQuery, "parseQuery");
2166         return new ClassicFormat(this, parseQuery);
2167     }
2168 
2169     //-----------------------------------------------------------------------
2170     /**
2171      * Returns a description of the underlying formatters.
2172      *
2173      * @return a description of this formatter, not null
2174      */
2175     @Override
2176     public String toString() {
2177         String pattern = printerParser.toString();
2178         pattern = pattern.startsWith("[") ? pattern : pattern.substring(1, pattern.length() - 1);
2179         return pattern;
2180         // TODO: Fix tests to not depend on toString()
2181 //        return "DateTimeFormatter[" + locale +
2182 //                (chrono != null ? "," + chrono : "") +
2183 //                (zone != null ? "," + zone : "") +
2184 //                pattern + "]";
2185     }
2186 
2187     //-----------------------------------------------------------------------
2188     /**
2189      * Implements the classic Java Format API.
2190      * @serial exclude
2191      */
2192     @SuppressWarnings("serial")  // not actually serializable
2193     static class ClassicFormat extends Format {
2194         /** The formatter. */
2195         private final DateTimeFormatter formatter;
2196         /** The type to be parsed. */
2197         private final TemporalQuery<?> parseType;
2198         /** Constructor. */
2199         public ClassicFormat(DateTimeFormatter formatter, TemporalQuery<?> parseType) {
2200             this.formatter = formatter;
2201             this.parseType = parseType;
2202         }
2203 
2204         @Override
2205         public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
2206             Objects.requireNonNull(obj, "obj");
2207             Objects.requireNonNull(toAppendTo, "toAppendTo");
2208             Objects.requireNonNull(pos, "pos");
2209             if (obj instanceof TemporalAccessor == false) {
2210                 throw new IllegalArgumentException("Format target must implement TemporalAccessor");
2211             }
2212             pos.setBeginIndex(0);
2213             pos.setEndIndex(0);
2214             try {
2215                 formatter.formatTo((TemporalAccessor) obj, toAppendTo);
2216             } catch (RuntimeException ex) {
2217                 throw new IllegalArgumentException(ex.getMessage(), ex);
2218             }
2219             return toAppendTo;
2220         }
2221         @Override
2222         public Object parseObject(String text) throws ParseException {
2223             Objects.requireNonNull(text, "text");
2224             try {
2225                 if (parseType == null) {
2226                     return formatter.parseResolved0(text, null);
2227                 }
2228                 return formatter.parse(text, parseType);
2229             } catch (DateTimeParseException ex) {
2230                 throw new ParseException(ex.getMessage(), ex.getErrorIndex());
2231             } catch (RuntimeException ex) {
2232                 throw (ParseException) new ParseException(ex.getMessage(), 0).initCause(ex);
2233             }
2234         }
2235         @Override
2236         public Object parseObject(String text, ParsePosition pos) {
2237             Objects.requireNonNull(text, "text");
2238             DateTimeParseContext context;
2239             try {
2240                 context = formatter.parseUnresolved0(text, pos);
2241             } catch (IndexOutOfBoundsException ex) {
2242                 if (pos.getErrorIndex() < 0) {
2243                     pos.setErrorIndex(0);
2244                 }
2245                 return null;
2246             }
2247             if (context == null) {
2248                 if (pos.getErrorIndex() < 0) {
2249                     pos.setErrorIndex(0);
2250                 }
2251                 return null;
2252             }
2253             try {
2254                 TemporalAccessor resolved = context.toResolved(formatter.resolverStyle, formatter.resolverFields);
2255                 if (parseType == null) {
2256                     return resolved;
2257                 }
2258                 return resolved.query(parseType);
2259             } catch (RuntimeException ex) {
2260                 pos.setErrorIndex(0);
2261                 return null;
2262             }
2263         }
2264     }
2265 
2266 }