1 /*
   2  * Copyright (c) 1996, 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  * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
  28  * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
  29  *
  30  *   The original version of this source code and documentation is copyrighted
  31  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  32  * materials are provided under terms of a License Agreement between Taligent
  33  * and Sun. This technology is protected by multiple US and International
  34  * patents. This notice and attribution to Taligent may not be removed.
  35  *   Taligent is a registered trademark of Taligent, Inc.
  36  *
  37  */
  38 
  39 package java.text;
  40 
  41 import java.io.IOException;
  42 import java.io.InvalidObjectException;
  43 import java.io.ObjectInputStream;
  44 import static java.text.DateFormatSymbols.*;
  45 import java.util.Calendar;
  46 import java.util.Date;
  47 import java.util.GregorianCalendar;
  48 import java.util.Locale;
  49 import java.util.Map;
  50 import java.util.SimpleTimeZone;
  51 import java.util.SortedMap;
  52 import java.util.TimeZone;
  53 import java.util.concurrent.ConcurrentHashMap;
  54 import java.util.concurrent.ConcurrentMap;
  55 import sun.util.calendar.CalendarUtils;
  56 import sun.util.calendar.ZoneInfoFile;
  57 import sun.util.locale.provider.LocaleProviderAdapter;
  58 import sun.util.locale.provider.TimeZoneNameUtility;
  59 
  60 /**
  61  * <code>SimpleDateFormat</code> is a concrete class for formatting and
  62  * parsing dates in a locale-sensitive manner. It allows for formatting
  63  * (date &rarr; text), parsing (text &rarr; date), and normalization.
  64  *
  65  * <p>
  66  * <code>SimpleDateFormat</code> allows you to start by choosing
  67  * any user-defined patterns for date-time formatting. However, you
  68  * are encouraged to create a date-time formatter with either
  69  * <code>getTimeInstance</code>, <code>getDateInstance</code>, or
  70  * <code>getDateTimeInstance</code> in <code>DateFormat</code>. Each
  71  * of these class methods can return a date/time formatter initialized
  72  * with a default format pattern. You may modify the format pattern
  73  * using the <code>applyPattern</code> methods as desired.
  74  * For more information on using these methods, see
  75  * {@link DateFormat}.
  76  *
  77  * <h2>Date and Time Patterns</h2>
  78  * <p>
  79  * Date and time formats are specified by <em>date and time pattern</em>
  80  * strings.
  81  * Within date and time pattern strings, unquoted letters from
  82  * <code>'A'</code> to <code>'Z'</code> and from <code>'a'</code> to
  83  * <code>'z'</code> are interpreted as pattern letters representing the
  84  * components of a date or time string.
  85  * Text can be quoted using single quotes (<code>'</code>) to avoid
  86  * interpretation.
  87  * <code>"''"</code> represents a single quote.
  88  * All other characters are not interpreted; they're simply copied into the
  89  * output string during formatting or matched against the input string
  90  * during parsing.
  91  * <p>
  92  * The following pattern letters are defined (all other characters from
  93  * <code>'A'</code> to <code>'Z'</code> and from <code>'a'</code> to
  94  * <code>'z'</code> are reserved):
  95  * <blockquote>
  96  * <table class="striped">
  97  * <caption style="display:none">Chart shows pattern letters, date/time component, presentation, and examples.</caption>
  98  * <thead>
  99  *     <tr>
 100  *         <th scope="col" style="text-align:left">Letter
 101  *         <th scope="col" style="text-align:left">Date or Time Component
 102  *         <th scope="col" style="text-align:left">Presentation
 103  *         <th scope="col" style="text-align:left">Examples
 104  * </thead>
 105  * <tbody>
 106  *     <tr>
 107  *         <th scope="row"><code>G</code>
 108  *         <td>Era designator
 109  *         <td><a href="#text">Text</a>
 110  *         <td><code>AD</code>
 111  *     <tr>
 112  *         <th scope="row"><code>y</code>
 113  *         <td>Year
 114  *         <td><a href="#year">Year</a>
 115  *         <td><code>1996</code>; <code>96</code>
 116  *     <tr>
 117  *         <th scope="row"><code>Y</code>
 118  *         <td>Week year
 119  *         <td><a href="#year">Year</a>
 120  *         <td><code>2009</code>; <code>09</code>
 121  *     <tr>
 122  *         <th scope="row"><code>M</code>
 123  *         <td>Month in year (context sensitive)
 124  *         <td><a href="#month">Month</a>
 125  *         <td><code>July</code>; <code>Jul</code>; <code>07</code>
 126  *     <tr>
 127  *         <th scope="row"><code>L</code>
 128  *         <td>Month in year (standalone form)
 129  *         <td><a href="#month">Month</a>
 130  *         <td><code>July</code>; <code>Jul</code>; <code>07</code>
 131  *     <tr>
 132  *         <th scope="row"><code>w</code>
 133  *         <td>Week in year
 134  *         <td><a href="#number">Number</a>
 135  *         <td><code>27</code>
 136  *     <tr>
 137  *         <th scope="row"><code>W</code>
 138  *         <td>Week in month
 139  *         <td><a href="#number">Number</a>
 140  *         <td><code>2</code>
 141  *     <tr>
 142  *         <th scope="row"><code>D</code>
 143  *         <td>Day in year
 144  *         <td><a href="#number">Number</a>
 145  *         <td><code>189</code>
 146  *     <tr>
 147  *         <th scope="row"><code>d</code>
 148  *         <td>Day in month
 149  *         <td><a href="#number">Number</a>
 150  *         <td><code>10</code>
 151  *     <tr>
 152  *         <th scope="row"><code>F</code>
 153  *         <td>Day of week in month
 154  *         <td><a href="#number">Number</a>
 155  *         <td><code>2</code>
 156  *     <tr>
 157  *         <th scope="row"><code>E</code>
 158  *         <td>Day name in week
 159  *         <td><a href="#text">Text</a>
 160  *         <td><code>Tuesday</code>; <code>Tue</code>
 161  *     <tr>
 162  *         <th scope="row"><code>u</code>
 163  *         <td>Day number of week (1 = Monday, ..., 7 = Sunday)
 164  *         <td><a href="#number">Number</a>
 165  *         <td><code>1</code>
 166  *     <tr>
 167  *         <th scope="row"><code>a</code>
 168  *         <td>Am/pm marker
 169  *         <td><a href="#text">Text</a>
 170  *         <td><code>PM</code>
 171  *     <tr>
 172  *         <th scope="row"><code>H</code>
 173  *         <td>Hour in day (0-23)
 174  *         <td><a href="#number">Number</a>
 175  *         <td><code>0</code>
 176  *     <tr>
 177  *         <th scope="row"><code>k</code>
 178  *         <td>Hour in day (1-24)
 179  *         <td><a href="#number">Number</a>
 180  *         <td><code>24</code>
 181  *     <tr>
 182  *         <th scope="row"><code>K</code>
 183  *         <td>Hour in am/pm (0-11)
 184  *         <td><a href="#number">Number</a>
 185  *         <td><code>0</code>
 186  *     <tr>
 187  *         <th scope="row"><code>h</code>
 188  *         <td>Hour in am/pm (1-12)
 189  *         <td><a href="#number">Number</a>
 190  *         <td><code>12</code>
 191  *     <tr>
 192  *         <th scope="row"><code>m</code>
 193  *         <td>Minute in hour
 194  *         <td><a href="#number">Number</a>
 195  *         <td><code>30</code>
 196  *     <tr>
 197  *         <th scope="row"><code>s</code>
 198  *         <td>Second in minute
 199  *         <td><a href="#number">Number</a>
 200  *         <td><code>55</code>
 201  *     <tr>
 202  *         <th scope="row"><code>S</code>
 203  *         <td>Millisecond
 204  *         <td><a href="#number">Number</a>
 205  *         <td><code>978</code>
 206  *     <tr>
 207  *         <th scope="row"><code>z</code>
 208  *         <td>Time zone
 209  *         <td><a href="#timezone">General time zone</a>
 210  *         <td><code>Pacific Standard Time</code>; <code>PST</code>; <code>GMT-08:00</code>
 211  *     <tr>
 212  *         <th scope="row"><code>Z</code>
 213  *         <td>Time zone
 214  *         <td><a href="#rfc822timezone">RFC 822 time zone</a>
 215  *         <td><code>-0800</code>
 216  *     <tr>
 217  *         <th scope="row"><code>X</code>
 218  *         <td>Time zone
 219  *         <td><a href="#iso8601timezone">ISO 8601 time zone</a>
 220  *         <td><code>-08</code>; <code>-0800</code>;  <code>-08:00</code>
 221  * </tbody>
 222  * </table>
 223  * </blockquote>
 224  * Pattern letters are usually repeated, as their number determines the
 225  * exact presentation:
 226  * <ul>
 227  * <li><strong><a id="text">Text:</a></strong>
 228  *     For formatting, if the number of pattern letters is 4 or more,
 229  *     the full form is used; otherwise a short or abbreviated form
 230  *     is used if available.
 231  *     For parsing, both forms are accepted, independent of the number
 232  *     of pattern letters.<br><br></li>
 233  * <li><strong><a id="number">Number:</a></strong>
 234  *     For formatting, the number of pattern letters is the minimum
 235  *     number of digits, and shorter numbers are zero-padded to this amount.
 236  *     For parsing, the number of pattern letters is ignored unless
 237  *     it's needed to separate two adjacent fields.<br><br></li>
 238  * <li><strong><a id="year">Year:</a></strong>
 239  *     If the formatter's {@link #getCalendar() Calendar} is the Gregorian
 240  *     calendar, the following rules are applied.<br>
 241  *     <ul>
 242  *     <li>For formatting, if the number of pattern letters is 2, the year
 243  *         is truncated to 2 digits; otherwise it is interpreted as a
 244  *         <a href="#number">number</a>.
 245  *     <li>For parsing, if the number of pattern letters is more than 2,
 246  *         the year is interpreted literally, regardless of the number of
 247  *         digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to
 248  *         Jan 11, 12 A.D.
 249  *     <li>For parsing with the abbreviated year pattern ("y" or "yy"),
 250  *         <code>SimpleDateFormat</code> must interpret the abbreviated year
 251  *         relative to some century.  It does this by adjusting dates to be
 252  *         within 80 years before and 20 years after the time the <code>SimpleDateFormat</code>
 253  *         instance is created. For example, using a pattern of "MM/dd/yy" and a
 254  *         <code>SimpleDateFormat</code> instance created on Jan 1, 1997,  the string
 255  *         "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64"
 256  *         would be interpreted as May 4, 1964.
 257  *         During parsing, only strings consisting of exactly two digits, as defined by
 258  *         {@link Character#isDigit(char)}, will be parsed into the default century.
 259  *         Any other numeric string, such as a one digit string, a three or more digit
 260  *         string, or a two digit string that isn't all digits (for example, "-1"), is
 261  *         interpreted literally.  So "01/02/3" or "01/02/003" are parsed, using the
 262  *         same pattern, as Jan 2, 3 AD.  Likewise, "01/02/-3" is parsed as Jan 2, 4 BC.
 263  *     </ul>
 264  *     Otherwise, calendar system specific forms are applied.
 265  *     For both formatting and parsing, if the number of pattern
 266  *     letters is 4 or more, a calendar specific {@linkplain
 267  *     Calendar#LONG long form} is used. Otherwise, a calendar
 268  *     specific {@linkplain Calendar#SHORT short or abbreviated form}
 269  *     is used.<br>
 270  *     <br>
 271  *     If week year {@code 'Y'} is specified and the {@linkplain
 272  *     #getCalendar() calendar} doesn't support any <a
 273  *     href="../util/GregorianCalendar.html#week_year"> week
 274  *     years</a>, the calendar year ({@code 'y'}) is used instead. The
 275  *     support of week years can be tested with a call to {@link
 276  *     DateFormat#getCalendar() getCalendar()}.{@link
 277  *     java.util.Calendar#isWeekDateSupported()
 278  *     isWeekDateSupported()}.<br><br></li>
 279  * <li><strong><a id="month">Month:</a></strong>
 280  *     If the number of pattern letters is 3 or more, the month is
 281  *     interpreted as <a href="#text">text</a>; otherwise,
 282  *     it is interpreted as a <a href="#number">number</a>.<br>
 283  *     <ul>
 284  *     <li>Letter <em>M</em> produces context-sensitive month names, such as the
 285  *         embedded form of names. Letter <em>M</em> is context-sensitive in the
 286  *         sense that when it is used in the standalone pattern, for example,
 287  *         "MMMM", it gives the standalone form of a month name and when it is
 288  *         used in the pattern containing other field(s), for example, "d MMMM",
 289  *         it gives the format form of a month name. For example, January in the
 290  *         Catalan language is "de gener" in the format form while it is "gener"
 291  *         in the standalone form. In this case, "MMMM" will produce "gener" and
 292  *         the month part of the "d MMMM" will produce "de gener". If a
 293  *         {@code DateFormatSymbols} has been set explicitly with constructor
 294  *         {@link #SimpleDateFormat(String,DateFormatSymbols)} or method {@link
 295  *         #setDateFormatSymbols(DateFormatSymbols)}, the month names given by
 296  *         the {@code DateFormatSymbols} are used.</li>
 297  *     <li>Letter <em>L</em> produces the standalone form of month names.</li>
 298  *     </ul>
 299  *     <br></li>
 300  * <li><strong><a id="timezone">General time zone:</a></strong>
 301  *     Time zones are interpreted as <a href="#text">text</a> if they have
 302  *     names. For time zones representing a GMT offset value, the
 303  *     following syntax is used:
 304  *     <pre>
 305  *     <a id="GMTOffsetTimeZone"><i>GMTOffsetTimeZone:</i></a>
 306  *             <code>GMT</code> <i>Sign</i> <i>Hours</i> <code>:</code> <i>Minutes</i>
 307  *     <i>Sign:</i> one of
 308  *             <code>+ -</code>
 309  *     <i>Hours:</i>
 310  *             <i>Digit</i>
 311  *             <i>Digit</i> <i>Digit</i>
 312  *     <i>Minutes:</i>
 313  *             <i>Digit</i> <i>Digit</i>
 314  *     <i>Digit:</i> one of
 315  *             <code>0 1 2 3 4 5 6 7 8 9</code></pre>
 316  *     <i>Hours</i> must be between 0 and 23, and <i>Minutes</i> must be between
 317  *     00 and 59. The format is locale independent and digits must be taken
 318  *     from the Basic Latin block of the Unicode standard.
 319  *     <p>For parsing, <a href="#rfc822timezone">RFC 822 time zones</a> are also
 320  *     accepted.<br><br></li>
 321  * <li><strong><a id="rfc822timezone">RFC 822 time zone:</a></strong>
 322  *     For formatting, the RFC 822 4-digit time zone format is used:
 323  *
 324  *     <pre>
 325  *     <i>RFC822TimeZone:</i>
 326  *             <i>Sign</i> <i>TwoDigitHours</i> <i>Minutes</i>
 327  *     <i>TwoDigitHours:</i>
 328  *             <i>Digit Digit</i></pre>
 329  *     <i>TwoDigitHours</i> must be between 00 and 23. Other definitions
 330  *     are as for <a href="#timezone">general time zones</a>.
 331  *
 332  *     <p>For parsing, <a href="#timezone">general time zones</a> are also
 333  *     accepted.
 334  * <li><strong><a id="iso8601timezone">ISO 8601 Time zone:</a></strong>
 335  *     The number of pattern letters designates the format for both formatting
 336  *     and parsing as follows:
 337  *     <pre>
 338  *     <i>ISO8601TimeZone:</i>
 339  *             <i>OneLetterISO8601TimeZone</i>
 340  *             <i>TwoLetterISO8601TimeZone</i>
 341  *             <i>ThreeLetterISO8601TimeZone</i>
 342  *     <i>OneLetterISO8601TimeZone:</i>
 343  *             <i>Sign</i> <i>TwoDigitHours</i>
 344  *             {@code Z}
 345  *     <i>TwoLetterISO8601TimeZone:</i>
 346  *             <i>Sign</i> <i>TwoDigitHours</i> <i>Minutes</i>
 347  *             {@code Z}
 348  *     <i>ThreeLetterISO8601TimeZone:</i>
 349  *             <i>Sign</i> <i>TwoDigitHours</i> {@code :} <i>Minutes</i>
 350  *             {@code Z}</pre>
 351  *     Other definitions are as for <a href="#timezone">general time zones</a> or
 352  *     <a href="#rfc822timezone">RFC 822 time zones</a>.
 353  *
 354  *     <p>For formatting, if the offset value from GMT is 0, {@code "Z"} is
 355  *     produced. If the number of pattern letters is 1, any fraction of an hour
 356  *     is ignored. For example, if the pattern is {@code "X"} and the time zone is
 357  *     {@code "GMT+05:30"}, {@code "+05"} is produced.
 358  *
 359  *     <p>For parsing, {@code "Z"} is parsed as the UTC time zone designator.
 360  *     <a href="#timezone">General time zones</a> are <em>not</em> accepted.
 361  *
 362  *     <p>If the number of pattern letters is 4 or more, {@link
 363  *     IllegalArgumentException} is thrown when constructing a {@code
 364  *     SimpleDateFormat} or {@linkplain #applyPattern(String) applying a
 365  *     pattern}.
 366  * </ul>
 367  * <code>SimpleDateFormat</code> also supports <em>localized date and time
 368  * pattern</em> strings. In these strings, the pattern letters described above
 369  * may be replaced with other, locale dependent, pattern letters.
 370  * <code>SimpleDateFormat</code> does not deal with the localization of text
 371  * other than the pattern letters; that's up to the client of the class.
 372  *
 373  * <h3>Examples</h3>
 374  *
 375  * The following examples show how date and time patterns are interpreted in
 376  * the U.S. locale. The given date and time are 2001-07-04 12:08:56 local time
 377  * in the U.S. Pacific Time time zone.
 378  * <blockquote>
 379  * <table class="striped">
 380  * <caption style="display:none">Examples of date and time patterns interpreted in the U.S. locale</caption>
 381  * <thead>
 382  *     <tr>
 383  *         <th scope="col" style="text-align:left">Date and Time Pattern
 384  *         <th scope="col" style="text-align:left">Result
 385  * </thead>
 386  * <tbody>
 387  *     <tr>
 388  *         <th scope="row"><code>"yyyy.MM.dd G 'at' HH:mm:ss z"</code>
 389  *         <td><code>2001.07.04 AD at 12:08:56 PDT</code>
 390  *     <tr>
 391  *         <th scope="row"><code>"EEE, MMM d, ''yy"</code>
 392  *         <td><code>Wed, Jul 4, '01</code>
 393  *     <tr>
 394  *         <th scope="row"><code>"h:mm a"</code>
 395  *         <td><code>12:08 PM</code>
 396  *     <tr>
 397  *         <th scope="row"><code>"hh 'o''clock' a, zzzz"</code>
 398  *         <td><code>12 o'clock PM, Pacific Daylight Time</code>
 399  *     <tr>
 400  *         <th scope="row"><code>"K:mm a, z"</code>
 401  *         <td><code>0:08 PM, PDT</code>
 402  *     <tr>
 403  *         <th scope="row"><code>"yyyyy.MMMMM.dd GGG hh:mm aaa"</code>
 404  *         <td><code>02001.July.04 AD 12:08 PM</code>
 405  *     <tr>
 406  *         <th scope="row"><code>"EEE, d MMM yyyy HH:mm:ss Z"</code>
 407  *         <td><code>Wed, 4 Jul 2001 12:08:56 -0700</code>
 408  *     <tr>
 409  *         <th scope="row"><code>"yyMMddHHmmssZ"</code>
 410  *         <td><code>010704120856-0700</code>
 411  *     <tr>
 412  *         <th scope="row"><code>"yyyy-MM-dd'T'HH:mm:ss.SSSZ"</code>
 413  *         <td><code>2001-07-04T12:08:56.235-0700</code>
 414  *     <tr>
 415  *         <th scope="row"><code>"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"</code>
 416  *         <td><code>2001-07-04T12:08:56.235-07:00</code>
 417  *     <tr>
 418  *         <th scope="row"><code>"YYYY-'W'ww-u"</code>
 419  *         <td><code>2001-W27-3</code>
 420  * </tbody>
 421  * </table>
 422  * </blockquote>
 423  *
 424  * <h3><a id="synchronization">Synchronization</a></h3>
 425  *
 426  * <p>
 427  * Date formats are not synchronized.
 428  * It is recommended to create separate format instances for each thread.
 429  * If multiple threads access a format concurrently, it must be synchronized
 430  * externally.
 431  *
 432  * @see          <a href="http://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html">Java Tutorial</a>
 433  * @see          java.util.Calendar
 434  * @see          java.util.TimeZone
 435  * @see          DateFormat
 436  * @see          DateFormatSymbols
 437  * @author       Mark Davis, Chen-Lieh Huang, Alan Liu
 438  * @since 1.1
 439  */
 440 public class SimpleDateFormat extends DateFormat {
 441 
 442     // the official serial version ID which says cryptically
 443     // which version we're compatible with
 444     @java.io.Serial
 445     static final long serialVersionUID = 4774881970558875024L;
 446 
 447     // the internal serial version which says which version was written
 448     // - 0 (default) for version up to JDK 1.1.3
 449     // - 1 for version from JDK 1.1.4, which includes a new field
 450     static final int currentSerialVersion = 1;
 451 
 452     /**
 453      * The version of the serialized data on the stream.  Possible values:
 454      * <ul>
 455      * <li><b>0</b> or not present on stream: JDK 1.1.3.  This version
 456      * has no <code>defaultCenturyStart</code> on stream.
 457      * <li><b>1</b> JDK 1.1.4 or later.  This version adds
 458      * <code>defaultCenturyStart</code>.
 459      * </ul>
 460      * When streaming out this class, the most recent format
 461      * and the highest allowable <code>serialVersionOnStream</code>
 462      * is written.
 463      * @serial
 464      * @since 1.1.4
 465      */
 466     private int serialVersionOnStream = currentSerialVersion;
 467 
 468     /**
 469      * The pattern string of this formatter.  This is always a non-localized
 470      * pattern.  May not be null.  See class documentation for details.
 471      * @serial
 472      */
 473     private String pattern;
 474 
 475     /**
 476      * Saved numberFormat and pattern.
 477      * @see SimpleDateFormat#checkNegativeNumberExpression
 478      */
 479     private transient NumberFormat originalNumberFormat;
 480     private transient String originalNumberPattern;
 481 
 482     /**
 483      * The minus sign to be used with format and parse.
 484      */
 485     private transient char minusSign = '-';
 486 
 487     /**
 488      * True when a negative sign follows a number.
 489      * (True as default in Arabic.)
 490      */
 491     private transient boolean hasFollowingMinusSign = false;
 492 
 493     /**
 494      * True if standalone form needs to be used.
 495      */
 496     private transient boolean forceStandaloneForm = false;
 497 
 498     /**
 499      * The compiled pattern.
 500      */
 501     private transient char[] compiledPattern;
 502 
 503     /**
 504      * Tags for the compiled pattern.
 505      */
 506     private static final int TAG_QUOTE_ASCII_CHAR       = 100;
 507     private static final int TAG_QUOTE_CHARS            = 101;
 508 
 509     /**
 510      * Locale dependent digit zero.
 511      * @see #zeroPaddingNumber
 512      * @see java.text.DecimalFormatSymbols#getZeroDigit
 513      */
 514     private transient char zeroDigit;
 515 
 516     /**
 517      * The symbols used by this formatter for week names, month names,
 518      * etc.  May not be null.
 519      * @serial
 520      * @see java.text.DateFormatSymbols
 521      */
 522     private DateFormatSymbols formatData;
 523 
 524     /**
 525      * We map dates with two-digit years into the century starting at
 526      * <code>defaultCenturyStart</code>, which may be any date.  May
 527      * not be null.
 528      * @serial
 529      * @since 1.1.4
 530      */
 531     private Date defaultCenturyStart;
 532 
 533     private transient int defaultCenturyStartYear;
 534 
 535     private static final int MILLIS_PER_MINUTE = 60 * 1000;
 536 
 537     // For time zones that have no names, use strings GMT+minutes and
 538     // GMT-minutes. For instance, in France the time zone is GMT+60.
 539     private static final String GMT = "GMT";
 540 
 541     /**
 542      * Cache NumberFormat instances with Locale key.
 543      */
 544     private static final ConcurrentMap<Locale, NumberFormat> cachedNumberFormatData
 545         = new ConcurrentHashMap<>(3);
 546 
 547     /**
 548      * The Locale used to instantiate this
 549      * <code>SimpleDateFormat</code>. The value may be null if this object
 550      * has been created by an older <code>SimpleDateFormat</code> and
 551      * deserialized.
 552      *
 553      * @serial
 554      * @since 1.6
 555      */
 556     private Locale locale;
 557 
 558     /**
 559      * Indicates whether this <code>SimpleDateFormat</code> should use
 560      * the DateFormatSymbols. If true, the format and parse methods
 561      * use the DateFormatSymbols values. If false, the format and
 562      * parse methods call Calendar.getDisplayName or
 563      * Calendar.getDisplayNames.
 564      */
 565     transient boolean useDateFormatSymbols;
 566 
 567     /**
 568      * Constructs a <code>SimpleDateFormat</code> using the default pattern and
 569      * date format symbols for the default
 570      * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 571      * <b>Note:</b> This constructor may not support all locales.
 572      * For full coverage, use the factory methods in the {@link DateFormat}
 573      * class.
 574      */
 575     public SimpleDateFormat() {
 576         this("", Locale.getDefault(Locale.Category.FORMAT));
 577         applyPatternImpl(LocaleProviderAdapter.getResourceBundleBased().getLocaleResources(locale)
 578                          .getDateTimePattern(SHORT, SHORT, calendar));
 579     }
 580 
 581     /**
 582      * Constructs a <code>SimpleDateFormat</code> using the given pattern and
 583      * the default date format symbols for the default
 584      * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 585      * <b>Note:</b> This constructor may not support all locales.
 586      * For full coverage, use the factory methods in the {@link DateFormat}
 587      * class.
 588      * <p>This is equivalent to calling
 589      * {@link #SimpleDateFormat(String, Locale)
 590      *     SimpleDateFormat(pattern, Locale.getDefault(Locale.Category.FORMAT))}.
 591      *
 592      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 593      * @see java.util.Locale.Category#FORMAT
 594      * @param pattern the pattern describing the date and time format
 595      * @exception NullPointerException if the given pattern is null
 596      * @exception IllegalArgumentException if the given pattern is invalid
 597      */
 598     public SimpleDateFormat(String pattern)
 599     {
 600         this(pattern, Locale.getDefault(Locale.Category.FORMAT));
 601     }
 602 
 603     /**
 604      * Constructs a <code>SimpleDateFormat</code> using the given pattern and
 605      * the default date format symbols for the given locale.
 606      * <b>Note:</b> This constructor may not support all locales.
 607      * For full coverage, use the factory methods in the {@link DateFormat}
 608      * class.
 609      *
 610      * @param pattern the pattern describing the date and time format
 611      * @param locale the locale whose date format symbols should be used
 612      * @exception NullPointerException if the given pattern or locale is null
 613      * @exception IllegalArgumentException if the given pattern is invalid
 614      */
 615     public SimpleDateFormat(String pattern, Locale locale)
 616     {
 617         if (pattern == null || locale == null) {
 618             throw new NullPointerException();
 619         }
 620 
 621         initializeCalendar(locale);
 622         this.pattern = pattern;
 623         this.formatData = DateFormatSymbols.getInstanceRef(locale);
 624         this.locale = locale;
 625         initialize(locale);
 626     }
 627 
 628     /**
 629      * Constructs a <code>SimpleDateFormat</code> using the given pattern and
 630      * date format symbols.
 631      *
 632      * @param pattern the pattern describing the date and time format
 633      * @param formatSymbols the date format symbols to be used for formatting
 634      * @exception NullPointerException if the given pattern or formatSymbols is null
 635      * @exception IllegalArgumentException if the given pattern is invalid
 636      */
 637     public SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)
 638     {
 639         if (pattern == null || formatSymbols == null) {
 640             throw new NullPointerException();
 641         }
 642 
 643         this.pattern = pattern;
 644         this.formatData = (DateFormatSymbols) formatSymbols.clone();
 645         this.locale = Locale.getDefault(Locale.Category.FORMAT);
 646         initializeCalendar(this.locale);
 647         initialize(this.locale);
 648         useDateFormatSymbols = true;
 649     }
 650 
 651     /* Initialize compiledPattern and numberFormat fields */
 652     private void initialize(Locale loc) {
 653         // Verify and compile the given pattern.
 654         compiledPattern = compile(pattern);
 655 
 656         /* try the cache first */
 657         numberFormat = cachedNumberFormatData.get(loc);
 658         if (numberFormat == null) { /* cache miss */
 659             numberFormat = NumberFormat.getIntegerInstance(loc);
 660             numberFormat.setGroupingUsed(false);
 661 
 662             /* update cache */
 663             cachedNumberFormatData.putIfAbsent(loc, numberFormat);
 664         }
 665         numberFormat = (NumberFormat) numberFormat.clone();
 666 
 667         initializeDefaultCentury();
 668     }
 669 
 670     private void initializeCalendar(Locale loc) {
 671         if (calendar == null) {
 672             assert loc != null;
 673             // The format object must be constructed using the symbols for this zone.
 674             // However, the calendar should use the current default TimeZone.
 675             // If this is not contained in the locale zone strings, then the zone
 676             // will be formatted using generic GMT+/-H:MM nomenclature.
 677             calendar = Calendar.getInstance(loc);
 678         }
 679     }
 680 
 681     /**
 682      * Returns the compiled form of the given pattern. The syntax of
 683      * the compiled pattern is:
 684      * <blockquote>
 685      * CompiledPattern:
 686      *     EntryList
 687      * EntryList:
 688      *     Entry
 689      *     EntryList Entry
 690      * Entry:
 691      *     TagField
 692      *     TagField data
 693      * TagField:
 694      *     Tag Length
 695      *     TaggedData
 696      * Tag:
 697      *     pattern_char_index
 698      *     TAG_QUOTE_CHARS
 699      * Length:
 700      *     short_length
 701      *     long_length
 702      * TaggedData:
 703      *     TAG_QUOTE_ASCII_CHAR ascii_char
 704      *
 705      * </blockquote>
 706      *
 707      * where `short_length' is an 8-bit unsigned integer between 0 and
 708      * 254.  `long_length' is a sequence of an 8-bit integer 255 and a
 709      * 32-bit signed integer value which is split into upper and lower
 710      * 16-bit fields in two char's. `pattern_char_index' is an 8-bit
 711      * integer between 0 and 18. `ascii_char' is an 7-bit ASCII
 712      * character value. `data' depends on its Tag value.
 713      * <p>
 714      * If Length is short_length, Tag and short_length are packed in a
 715      * single char, as illustrated below.
 716      * <blockquote>
 717      *     char[0] = (Tag << 8) | short_length;
 718      * </blockquote>
 719      *
 720      * If Length is long_length, Tag and 255 are packed in the first
 721      * char and a 32-bit integer, as illustrated below.
 722      * <blockquote>
 723      *     char[0] = (Tag << 8) | 255;
 724      *     char[1] = (char) (long_length >>> 16);
 725      *     char[2] = (char) (long_length & 0xffff);
 726      * </blockquote>
 727      * <p>
 728      * If Tag is a pattern_char_index, its Length is the number of
 729      * pattern characters. For example, if the given pattern is
 730      * "yyyy", Tag is 1 and Length is 4, followed by no data.
 731      * <p>
 732      * If Tag is TAG_QUOTE_CHARS, its Length is the number of char's
 733      * following the TagField. For example, if the given pattern is
 734      * "'o''clock'", Length is 7 followed by a char sequence of
 735      * <code>o&nbs;'&nbs;c&nbs;l&nbs;o&nbs;c&nbs;k</code>.
 736      * <p>
 737      * TAG_QUOTE_ASCII_CHAR is a special tag and has an ASCII
 738      * character in place of Length. For example, if the given pattern
 739      * is "'o'", the TaggedData entry is
 740      * <code>((TAG_QUOTE_ASCII_CHAR&nbs;<<&nbs;8)&nbs;|&nbs;'o')</code>.
 741      *
 742      * @exception NullPointerException if the given pattern is null
 743      * @exception IllegalArgumentException if the given pattern is invalid
 744      */
 745     private char[] compile(String pattern) {
 746         int length = pattern.length();
 747         boolean inQuote = false;
 748         StringBuilder compiledCode = new StringBuilder(length * 2);
 749         StringBuilder tmpBuffer = null;
 750         int count = 0, tagcount = 0;
 751         int lastTag = -1, prevTag = -1;
 752 
 753         for (int i = 0; i < length; i++) {
 754             char c = pattern.charAt(i);
 755 
 756             if (c == '\'') {
 757                 // '' is treated as a single quote regardless of being
 758                 // in a quoted section.
 759                 if ((i + 1) < length) {
 760                     c = pattern.charAt(i + 1);
 761                     if (c == '\'') {
 762                         i++;
 763                         if (count != 0) {
 764                             encode(lastTag, count, compiledCode);
 765                             tagcount++;
 766                             prevTag = lastTag;
 767                             lastTag = -1;
 768                             count = 0;
 769                         }
 770                         if (inQuote) {
 771                             tmpBuffer.append(c);
 772                         } else {
 773                             compiledCode.append((char)(TAG_QUOTE_ASCII_CHAR << 8 | c));
 774                         }
 775                         continue;
 776                     }
 777                 }
 778                 if (!inQuote) {
 779                     if (count != 0) {
 780                         encode(lastTag, count, compiledCode);
 781                         tagcount++;
 782                         prevTag = lastTag;
 783                         lastTag = -1;
 784                         count = 0;
 785                     }
 786                     if (tmpBuffer == null) {
 787                         tmpBuffer = new StringBuilder(length);
 788                     } else {
 789                         tmpBuffer.setLength(0);
 790                     }
 791                     inQuote = true;
 792                 } else {
 793                     int len = tmpBuffer.length();
 794                     if (len == 1) {
 795                         char ch = tmpBuffer.charAt(0);
 796                         if (ch < 128) {
 797                             compiledCode.append((char)(TAG_QUOTE_ASCII_CHAR << 8 | ch));
 798                         } else {
 799                             compiledCode.append((char)(TAG_QUOTE_CHARS << 8 | 1));
 800                             compiledCode.append(ch);
 801                         }
 802                     } else {
 803                         encode(TAG_QUOTE_CHARS, len, compiledCode);
 804                         compiledCode.append(tmpBuffer);
 805                     }
 806                     inQuote = false;
 807                 }
 808                 continue;
 809             }
 810             if (inQuote) {
 811                 tmpBuffer.append(c);
 812                 continue;
 813             }
 814             if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
 815                 if (count != 0) {
 816                     encode(lastTag, count, compiledCode);
 817                     tagcount++;
 818                     prevTag = lastTag;
 819                     lastTag = -1;
 820                     count = 0;
 821                 }
 822                 if (c < 128) {
 823                     // In most cases, c would be a delimiter, such as ':'.
 824                     compiledCode.append((char)(TAG_QUOTE_ASCII_CHAR << 8 | c));
 825                 } else {
 826                     // Take any contiguous non-ASCII alphabet characters and
 827                     // put them in a single TAG_QUOTE_CHARS.
 828                     int j;
 829                     for (j = i + 1; j < length; j++) {
 830                         char d = pattern.charAt(j);
 831                         if (d == '\'' || (d >= 'a' && d <= 'z' || d >= 'A' && d <= 'Z')) {
 832                             break;
 833                         }
 834                     }
 835                     encode(TAG_QUOTE_CHARS, j - i, compiledCode);
 836                     for (; i < j; i++) {
 837                         compiledCode.append(pattern.charAt(i));
 838                     }
 839                     i--;
 840                 }
 841                 continue;
 842             }
 843 
 844             int tag;
 845             if ((tag = DateFormatSymbols.patternChars.indexOf(c)) == -1) {
 846                 throw new IllegalArgumentException("Illegal pattern character " +
 847                                                    "'" + c + "'");
 848             }
 849             if (lastTag == -1 || lastTag == tag) {
 850                 lastTag = tag;
 851                 count++;
 852                 continue;
 853             }
 854             encode(lastTag, count, compiledCode);
 855             tagcount++;
 856             prevTag = lastTag;
 857             lastTag = tag;
 858             count = 1;
 859         }
 860 
 861         if (inQuote) {
 862             throw new IllegalArgumentException("Unterminated quote");
 863         }
 864 
 865         if (count != 0) {
 866             encode(lastTag, count, compiledCode);
 867             tagcount++;
 868             prevTag = lastTag;
 869         }
 870 
 871         forceStandaloneForm = (tagcount == 1 && prevTag == PATTERN_MONTH);
 872 
 873         // Copy the compiled pattern to a char array
 874         int len = compiledCode.length();
 875         char[] r = new char[len];
 876         compiledCode.getChars(0, len, r, 0);
 877         return r;
 878     }
 879 
 880     /**
 881      * Encodes the given tag and length and puts encoded char(s) into buffer.
 882      */
 883     private static void encode(int tag, int length, StringBuilder buffer) {
 884         if (tag == PATTERN_ISO_ZONE && length >= 4) {
 885             throw new IllegalArgumentException("invalid ISO 8601 format: length=" + length);
 886         }
 887         if (length < 255) {
 888             buffer.append((char)(tag << 8 | length));
 889         } else {
 890             buffer.append((char)((tag << 8) | 0xff));
 891             buffer.append((char)(length >>> 16));
 892             buffer.append((char)(length & 0xffff));
 893         }
 894     }
 895 
 896     /* Initialize the fields we use to disambiguate ambiguous years. Separate
 897      * so we can call it from readObject().
 898      */
 899     private void initializeDefaultCentury() {
 900         calendar.setTimeInMillis(System.currentTimeMillis());
 901         calendar.add( Calendar.YEAR, -80 );
 902         parseAmbiguousDatesAsAfter(calendar.getTime());
 903     }
 904 
 905     /* Define one-century window into which to disambiguate dates using
 906      * two-digit years.
 907      */
 908     private void parseAmbiguousDatesAsAfter(Date startDate) {
 909         defaultCenturyStart = startDate;
 910         calendar.setTime(startDate);
 911         defaultCenturyStartYear = calendar.get(Calendar.YEAR);
 912     }
 913 
 914     /**
 915      * Sets the 100-year period 2-digit years will be interpreted as being in
 916      * to begin on the date the user specifies.
 917      *
 918      * @param startDate During parsing, two digit years will be placed in the range
 919      * <code>startDate</code> to <code>startDate + 100 years</code>.
 920      * @see #get2DigitYearStart
 921      * @throws NullPointerException if {@code startDate} is {@code null}.
 922      * @since 1.2
 923      */
 924     public void set2DigitYearStart(Date startDate) {
 925         parseAmbiguousDatesAsAfter(new Date(startDate.getTime()));
 926     }
 927 
 928     /**
 929      * Returns the beginning date of the 100-year period 2-digit years are interpreted
 930      * as being within.
 931      *
 932      * @return the start of the 100-year period into which two digit years are
 933      * parsed
 934      * @see #set2DigitYearStart
 935      * @since 1.2
 936      */
 937     public Date get2DigitYearStart() {
 938         return (Date) defaultCenturyStart.clone();
 939     }
 940 
 941     /**
 942      * Formats the given <code>Date</code> into a date/time string and appends
 943      * the result to the given <code>StringBuffer</code>.
 944      *
 945      * @param date the date-time value to be formatted into a date-time string.
 946      * @param toAppendTo where the new date-time text is to be appended.
 947      * @param pos keeps track on the position of the field within
 948      * the returned string. For example, given a date-time text
 949      * {@code "1996.07.10 AD at 15:08:56 PDT"}, if the given {@code fieldPosition}
 950      * is {@link DateFormat#YEAR_FIELD}, the begin index and end index of
 951      * {@code fieldPosition} will be set to 0 and 4, respectively.
 952      * Notice that if the same date-time field appears more than once in a
 953      * pattern, the {@code fieldPosition} will be set for the first occurrence
 954      * of that date-time field. For instance, formatting a {@code Date} to the
 955      * date-time string {@code "1 PM PDT (Pacific Daylight Time)"} using the
 956      * pattern {@code "h a z (zzzz)"} and the alignment field
 957      * {@link DateFormat#TIMEZONE_FIELD}, the begin index and end index of
 958      * {@code fieldPosition} will be set to 5 and 8, respectively, for the
 959      * first occurrence of the timezone pattern character {@code 'z'}.
 960      * @return the formatted date-time string.
 961      * @exception NullPointerException if any of the parameters is {@code null}.
 962      */
 963     @Override
 964     public StringBuffer format(Date date, StringBuffer toAppendTo,
 965                                FieldPosition pos)
 966     {
 967         pos.beginIndex = pos.endIndex = 0;
 968         return format(date, toAppendTo, pos.getFieldDelegate());
 969     }
 970 
 971     // Called from Format after creating a FieldDelegate
 972     private StringBuffer format(Date date, StringBuffer toAppendTo,
 973                                 FieldDelegate delegate) {
 974         // Convert input date to time field list
 975         calendar.setTime(date);
 976 
 977         boolean useDateFormatSymbols = useDateFormatSymbols();
 978 
 979         for (int i = 0; i < compiledPattern.length; ) {
 980             int tag = compiledPattern[i] >>> 8;
 981             int count = compiledPattern[i++] & 0xff;
 982             if (count == 255) {
 983                 count = compiledPattern[i++] << 16;
 984                 count |= compiledPattern[i++];
 985             }
 986 
 987             switch (tag) {
 988             case TAG_QUOTE_ASCII_CHAR:
 989                 toAppendTo.append((char)count);
 990                 break;
 991 
 992             case TAG_QUOTE_CHARS:
 993                 toAppendTo.append(compiledPattern, i, count);
 994                 i += count;
 995                 break;
 996 
 997             default:
 998                 subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
 999                 break;
1000             }
1001         }
1002         return toAppendTo;
1003     }
1004 
1005     /**
1006      * Formats an Object producing an <code>AttributedCharacterIterator</code>.
1007      * You can use the returned <code>AttributedCharacterIterator</code>
1008      * to build the resulting String, as well as to determine information
1009      * about the resulting String.
1010      * <p>
1011      * Each attribute key of the AttributedCharacterIterator will be of type
1012      * <code>DateFormat.Field</code>, with the corresponding attribute value
1013      * being the same as the attribute key.
1014      *
1015      * @exception NullPointerException if obj is null.
1016      * @exception IllegalArgumentException if the Format cannot format the
1017      *            given object, or if the Format's pattern string is invalid.
1018      * @param obj The object to format
1019      * @return AttributedCharacterIterator describing the formatted value.
1020      * @since 1.4
1021      */
1022     @Override
1023     public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
1024         StringBuffer sb = new StringBuffer();
1025         CharacterIteratorFieldDelegate delegate = new
1026                          CharacterIteratorFieldDelegate();
1027 
1028         if (obj instanceof Date) {
1029             format((Date)obj, sb, delegate);
1030         }
1031         else if (obj instanceof Number) {
1032             format(new Date(((Number)obj).longValue()), sb, delegate);
1033         }
1034         else if (obj == null) {
1035             throw new NullPointerException(
1036                    "formatToCharacterIterator must be passed non-null object");
1037         }
1038         else {
1039             throw new IllegalArgumentException(
1040                              "Cannot format given Object as a Date");
1041         }
1042         return delegate.getIterator(sb.toString());
1043     }
1044 
1045     // Map index into pattern character string to Calendar field number
1046     private static final int[] PATTERN_INDEX_TO_CALENDAR_FIELD = {
1047         Calendar.ERA,
1048         Calendar.YEAR,
1049         Calendar.MONTH,
1050         Calendar.DATE,
1051         Calendar.HOUR_OF_DAY,
1052         Calendar.HOUR_OF_DAY,
1053         Calendar.MINUTE,
1054         Calendar.SECOND,
1055         Calendar.MILLISECOND,
1056         Calendar.DAY_OF_WEEK,
1057         Calendar.DAY_OF_YEAR,
1058         Calendar.DAY_OF_WEEK_IN_MONTH,
1059         Calendar.WEEK_OF_YEAR,
1060         Calendar.WEEK_OF_MONTH,
1061         Calendar.AM_PM,
1062         Calendar.HOUR,
1063         Calendar.HOUR,
1064         Calendar.ZONE_OFFSET,
1065         Calendar.ZONE_OFFSET,
1066         CalendarBuilder.WEEK_YEAR,         // Pseudo Calendar field
1067         CalendarBuilder.ISO_DAY_OF_WEEK,   // Pseudo Calendar field
1068         Calendar.ZONE_OFFSET,
1069         Calendar.MONTH
1070     };
1071 
1072     // Map index into pattern character string to DateFormat field number
1073     private static final int[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD = {
1074         DateFormat.ERA_FIELD,
1075         DateFormat.YEAR_FIELD,
1076         DateFormat.MONTH_FIELD,
1077         DateFormat.DATE_FIELD,
1078         DateFormat.HOUR_OF_DAY1_FIELD,
1079         DateFormat.HOUR_OF_DAY0_FIELD,
1080         DateFormat.MINUTE_FIELD,
1081         DateFormat.SECOND_FIELD,
1082         DateFormat.MILLISECOND_FIELD,
1083         DateFormat.DAY_OF_WEEK_FIELD,
1084         DateFormat.DAY_OF_YEAR_FIELD,
1085         DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD,
1086         DateFormat.WEEK_OF_YEAR_FIELD,
1087         DateFormat.WEEK_OF_MONTH_FIELD,
1088         DateFormat.AM_PM_FIELD,
1089         DateFormat.HOUR1_FIELD,
1090         DateFormat.HOUR0_FIELD,
1091         DateFormat.TIMEZONE_FIELD,
1092         DateFormat.TIMEZONE_FIELD,
1093         DateFormat.YEAR_FIELD,
1094         DateFormat.DAY_OF_WEEK_FIELD,
1095         DateFormat.TIMEZONE_FIELD,
1096         DateFormat.MONTH_FIELD
1097     };
1098 
1099     // Maps from DecimalFormatSymbols index to Field constant
1100     private static final Field[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID = {
1101         Field.ERA,
1102         Field.YEAR,
1103         Field.MONTH,
1104         Field.DAY_OF_MONTH,
1105         Field.HOUR_OF_DAY1,
1106         Field.HOUR_OF_DAY0,
1107         Field.MINUTE,
1108         Field.SECOND,
1109         Field.MILLISECOND,
1110         Field.DAY_OF_WEEK,
1111         Field.DAY_OF_YEAR,
1112         Field.DAY_OF_WEEK_IN_MONTH,
1113         Field.WEEK_OF_YEAR,
1114         Field.WEEK_OF_MONTH,
1115         Field.AM_PM,
1116         Field.HOUR1,
1117         Field.HOUR0,
1118         Field.TIME_ZONE,
1119         Field.TIME_ZONE,
1120         Field.YEAR,
1121         Field.DAY_OF_WEEK,
1122         Field.TIME_ZONE,
1123         Field.MONTH
1124     };
1125 
1126     /**
1127      * Private member function that does the real date/time formatting.
1128      */
1129     private void subFormat(int patternCharIndex, int count,
1130                            FieldDelegate delegate, StringBuffer buffer,
1131                            boolean useDateFormatSymbols)
1132     {
1133         int     maxIntCount = Integer.MAX_VALUE;
1134         String  current = null;
1135         int     beginOffset = buffer.length();
1136 
1137         int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
1138         int value;
1139         if (field == CalendarBuilder.WEEK_YEAR) {
1140             if (calendar.isWeekDateSupported()) {
1141                 value = calendar.getWeekYear();
1142             } else {
1143                 // use calendar year 'y' instead
1144                 patternCharIndex = PATTERN_YEAR;
1145                 field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
1146                 value = calendar.get(field);
1147             }
1148         } else if (field == CalendarBuilder.ISO_DAY_OF_WEEK) {
1149             value = CalendarBuilder.toISODayOfWeek(calendar.get(Calendar.DAY_OF_WEEK));
1150         } else {
1151             value = calendar.get(field);
1152         }
1153 
1154         int style = (count >= 4) ? Calendar.LONG : Calendar.SHORT;
1155         if (!useDateFormatSymbols && field < Calendar.ZONE_OFFSET
1156             && patternCharIndex != PATTERN_MONTH_STANDALONE) {
1157             current = calendar.getDisplayName(field, style, locale);
1158         }
1159 
1160         // Note: zeroPaddingNumber() assumes that maxDigits is either
1161         // 2 or maxIntCount. If we make any changes to this,
1162         // zeroPaddingNumber() must be fixed.
1163 
1164         switch (patternCharIndex) {
1165         case PATTERN_ERA: // 'G'
1166             if (useDateFormatSymbols) {
1167                 String[] eras = formatData.getEras();
1168                 if (value < eras.length) {
1169                     current = eras[value];
1170                 }
1171             }
1172             if (current == null) {
1173                 current = "";
1174             }
1175             break;
1176 
1177         case PATTERN_WEEK_YEAR: // 'Y'
1178         case PATTERN_YEAR:      // 'y'
1179             if (calendar instanceof GregorianCalendar) {
1180                 if (count != 2) {
1181                     zeroPaddingNumber(value, count, maxIntCount, buffer);
1182                 } else {
1183                     zeroPaddingNumber(value, 2, 2, buffer);
1184                 } // clip 1996 to 96
1185             } else {
1186                 if (current == null) {
1187                     zeroPaddingNumber(value, style == Calendar.LONG ? 1 : count,
1188                                       maxIntCount, buffer);
1189                 }
1190             }
1191             break;
1192 
1193         case PATTERN_MONTH:            // 'M' (context sensitive)
1194             if (useDateFormatSymbols) {
1195                 String[] months;
1196                 if (count >= 4) {
1197                     months = formatData.getMonths();
1198                     current = months[value];
1199                 } else if (count == 3) {
1200                     months = formatData.getShortMonths();
1201                     current = months[value];
1202                 }
1203             } else {
1204                 if (count < 3) {
1205                     current = null;
1206                 } else if (forceStandaloneForm) {
1207                     current = calendar.getDisplayName(field, style | 0x8000, locale);
1208                     if (current == null) {
1209                         current = calendar.getDisplayName(field, style, locale);
1210                     }
1211                 }
1212             }
1213             if (current == null) {
1214                 zeroPaddingNumber(value+1, count, maxIntCount, buffer);
1215             }
1216             break;
1217 
1218         case PATTERN_MONTH_STANDALONE: // 'L'
1219             assert current == null;
1220             if (locale == null) {
1221                 String[] months;
1222                 if (count >= 4) {
1223                     months = formatData.getMonths();
1224                     current = months[value];
1225                 } else if (count == 3) {
1226                     months = formatData.getShortMonths();
1227                     current = months[value];
1228                 }
1229             } else {
1230                 if (count >= 3) {
1231                     current = calendar.getDisplayName(field, style | 0x8000, locale);
1232                 }
1233             }
1234             if (current == null) {
1235                 zeroPaddingNumber(value+1, count, maxIntCount, buffer);
1236             }
1237             break;
1238 
1239         case PATTERN_HOUR_OF_DAY1: // 'k' 1-based.  eg, 23:59 + 1 hour =>> 24:59
1240             if (current == null) {
1241                 if (value == 0) {
1242                     zeroPaddingNumber(calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1,
1243                                       count, maxIntCount, buffer);
1244                 } else {
1245                     zeroPaddingNumber(value, count, maxIntCount, buffer);
1246                 }
1247             }
1248             break;
1249 
1250         case PATTERN_DAY_OF_WEEK: // 'E'
1251             if (useDateFormatSymbols) {
1252                 String[] weekdays;
1253                 if (count >= 4) {
1254                     weekdays = formatData.getWeekdays();
1255                     current = weekdays[value];
1256                 } else { // count < 4, use abbreviated form if exists
1257                     weekdays = formatData.getShortWeekdays();
1258                     current = weekdays[value];
1259                 }
1260             }
1261             break;
1262 
1263         case PATTERN_AM_PM:    // 'a'
1264             if (useDateFormatSymbols) {
1265                 String[] ampm = formatData.getAmPmStrings();
1266                 current = ampm[value];
1267             }
1268             break;
1269 
1270         case PATTERN_HOUR1:    // 'h' 1-based.  eg, 11PM + 1 hour =>> 12 AM
1271             if (current == null) {
1272                 if (value == 0) {
1273                     zeroPaddingNumber(calendar.getLeastMaximum(Calendar.HOUR) + 1,
1274                                       count, maxIntCount, buffer);
1275                 } else {
1276                     zeroPaddingNumber(value, count, maxIntCount, buffer);
1277                 }
1278             }
1279             break;
1280 
1281         case PATTERN_ZONE_NAME: // 'z'
1282             if (current == null) {
1283                 if (formatData.locale == null || formatData.isZoneStringsSet) {
1284                     int zoneIndex =
1285                         formatData.getZoneIndex(calendar.getTimeZone().getID());
1286                     if (zoneIndex == -1) {
1287                         value = calendar.get(Calendar.ZONE_OFFSET) +
1288                             calendar.get(Calendar.DST_OFFSET);
1289                         buffer.append(ZoneInfoFile.toCustomID(value));
1290                     } else {
1291                         int index = (calendar.get(Calendar.DST_OFFSET) == 0) ? 1: 3;
1292                         if (count < 4) {
1293                             // Use the short name
1294                             index++;
1295                         }
1296                         String[][] zoneStrings = formatData.getZoneStringsWrapper();
1297                         buffer.append(zoneStrings[zoneIndex][index]);
1298                     }
1299                 } else {
1300                     TimeZone tz = calendar.getTimeZone();
1301                     boolean daylight = (calendar.get(Calendar.DST_OFFSET) != 0);
1302                     int tzstyle = (count < 4 ? TimeZone.SHORT : TimeZone.LONG);
1303                     buffer.append(tz.getDisplayName(daylight, tzstyle, formatData.locale));
1304                 }
1305             }
1306             break;
1307 
1308         case PATTERN_ZONE_VALUE: // 'Z' ("-/+hhmm" form)
1309             value = (calendar.get(Calendar.ZONE_OFFSET) +
1310                      calendar.get(Calendar.DST_OFFSET)) / 60000;
1311 
1312             int width = 4;
1313             if (value >= 0) {
1314                 buffer.append('+');
1315             } else {
1316                 width++;
1317             }
1318 
1319             int num = (value / 60) * 100 + (value % 60);
1320             CalendarUtils.sprintf0d(buffer, num, width);
1321             break;
1322 
1323         case PATTERN_ISO_ZONE:   // 'X'
1324             value = calendar.get(Calendar.ZONE_OFFSET)
1325                     + calendar.get(Calendar.DST_OFFSET);
1326 
1327             if (value == 0) {
1328                 buffer.append('Z');
1329                 break;
1330             }
1331 
1332             value /=  60000;
1333             if (value >= 0) {
1334                 buffer.append('+');
1335             } else {
1336                 buffer.append('-');
1337                 value = -value;
1338             }
1339 
1340             CalendarUtils.sprintf0d(buffer, value / 60, 2);
1341             if (count == 1) {
1342                 break;
1343             }
1344 
1345             if (count == 3) {
1346                 buffer.append(':');
1347             }
1348             CalendarUtils.sprintf0d(buffer, value % 60, 2);
1349             break;
1350 
1351         default:
1352      // case PATTERN_DAY_OF_MONTH:         // 'd'
1353      // case PATTERN_HOUR_OF_DAY0:         // 'H' 0-based.  eg, 23:59 + 1 hour =>> 00:59
1354      // case PATTERN_MINUTE:               // 'm'
1355      // case PATTERN_SECOND:               // 's'
1356      // case PATTERN_MILLISECOND:          // 'S'
1357      // case PATTERN_DAY_OF_YEAR:          // 'D'
1358      // case PATTERN_DAY_OF_WEEK_IN_MONTH: // 'F'
1359      // case PATTERN_WEEK_OF_YEAR:         // 'w'
1360      // case PATTERN_WEEK_OF_MONTH:        // 'W'
1361      // case PATTERN_HOUR0:                // 'K' eg, 11PM + 1 hour =>> 0 AM
1362      // case PATTERN_ISO_DAY_OF_WEEK:      // 'u' pseudo field, Monday = 1, ..., Sunday = 7
1363             if (current == null) {
1364                 zeroPaddingNumber(value, count, maxIntCount, buffer);
1365             }
1366             break;
1367         } // switch (patternCharIndex)
1368 
1369         if (current != null) {
1370             buffer.append(current);
1371         }
1372 
1373         int fieldID = PATTERN_INDEX_TO_DATE_FORMAT_FIELD[patternCharIndex];
1374         Field f = PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID[patternCharIndex];
1375 
1376         delegate.formatted(fieldID, f, f, beginOffset, buffer.length(), buffer);
1377     }
1378 
1379     /**
1380      * Formats a number with the specified minimum and maximum number of digits.
1381      */
1382     private void zeroPaddingNumber(int value, int minDigits, int maxDigits, StringBuffer buffer)
1383     {
1384         // Optimization for 1, 2 and 4 digit numbers. This should
1385         // cover most cases of formatting date/time related items.
1386         // Note: This optimization code assumes that maxDigits is
1387         // either 2 or Integer.MAX_VALUE (maxIntCount in format()).
1388         try {
1389             if (zeroDigit == 0) {
1390                 zeroDigit = ((DecimalFormat)numberFormat).getDecimalFormatSymbols().getZeroDigit();
1391             }
1392             if (value >= 0) {
1393                 if (value < 100 && minDigits >= 1 && minDigits <= 2) {
1394                     if (value < 10) {
1395                         if (minDigits == 2) {
1396                             buffer.append(zeroDigit);
1397                         }
1398                         buffer.append((char)(zeroDigit + value));
1399                     } else {
1400                         buffer.append((char)(zeroDigit + value / 10));
1401                         buffer.append((char)(zeroDigit + value % 10));
1402                     }
1403                     return;
1404                 } else if (value >= 1000 && value < 10000) {
1405                     if (minDigits == 4) {
1406                         buffer.append((char)(zeroDigit + value / 1000));
1407                         value %= 1000;
1408                         buffer.append((char)(zeroDigit + value / 100));
1409                         value %= 100;
1410                         buffer.append((char)(zeroDigit + value / 10));
1411                         buffer.append((char)(zeroDigit + value % 10));
1412                         return;
1413                     }
1414                     if (minDigits == 2 && maxDigits == 2) {
1415                         zeroPaddingNumber(value % 100, 2, 2, buffer);
1416                         return;
1417                     }
1418                 }
1419             }
1420         } catch (Exception e) {
1421         }
1422 
1423         numberFormat.setMinimumIntegerDigits(minDigits);
1424         numberFormat.setMaximumIntegerDigits(maxDigits);
1425         numberFormat.format((long)value, buffer, DontCareFieldPosition.INSTANCE);
1426     }
1427 
1428 
1429     /**
1430      * Parses text from a string to produce a <code>Date</code>.
1431      * <p>
1432      * The method attempts to parse text starting at the index given by
1433      * <code>pos</code>.
1434      * If parsing succeeds, then the index of <code>pos</code> is updated
1435      * to the index after the last character used (parsing does not necessarily
1436      * use all characters up to the end of the string), and the parsed
1437      * date is returned. The updated <code>pos</code> can be used to
1438      * indicate the starting point for the next call to this method.
1439      * If an error occurs, then the index of <code>pos</code> is not
1440      * changed, the error index of <code>pos</code> is set to the index of
1441      * the character where the error occurred, and null is returned.
1442      *
1443      * <p>This parsing operation uses the {@link DateFormat#calendar
1444      * calendar} to produce a {@code Date}. All of the {@code
1445      * calendar}'s date-time fields are {@linkplain Calendar#clear()
1446      * cleared} before parsing, and the {@code calendar}'s default
1447      * values of the date-time fields are used for any missing
1448      * date-time information. For example, the year value of the
1449      * parsed {@code Date} is 1970 with {@link GregorianCalendar} if
1450      * no year value is given from the parsing operation.  The {@code
1451      * TimeZone} value may be overwritten, depending on the given
1452      * pattern and the time zone value in {@code text}. Any {@code
1453      * TimeZone} value that has previously been set by a call to
1454      * {@link #setTimeZone(java.util.TimeZone) setTimeZone} may need
1455      * to be restored for further operations.
1456      *
1457      * @param text  A <code>String</code>, part of which should be parsed.
1458      * @param pos   A <code>ParsePosition</code> object with index and error
1459      *              index information as described above.
1460      * @return A <code>Date</code> parsed from the string. In case of
1461      *         error, returns null.
1462      * @exception NullPointerException if <code>text</code> or <code>pos</code> is null.
1463      */
1464     @Override
1465     public Date parse(String text, ParsePosition pos)
1466     {
1467         checkNegativeNumberExpression();
1468 
1469         int start = pos.index;
1470         int oldStart = start;
1471         int textLength = text.length();
1472 
1473         boolean[] ambiguousYear = {false};
1474 
1475         CalendarBuilder calb = new CalendarBuilder();
1476 
1477         for (int i = 0; i < compiledPattern.length; ) {
1478             int tag = compiledPattern[i] >>> 8;
1479             int count = compiledPattern[i++] & 0xff;
1480             if (count == 255) {
1481                 count = compiledPattern[i++] << 16;
1482                 count |= compiledPattern[i++];
1483             }
1484 
1485             switch (tag) {
1486             case TAG_QUOTE_ASCII_CHAR:
1487                 if (start >= textLength || text.charAt(start) != (char)count) {
1488                     pos.index = oldStart;
1489                     pos.errorIndex = start;
1490                     return null;
1491                 }
1492                 start++;
1493                 break;
1494 
1495             case TAG_QUOTE_CHARS:
1496                 while (count-- > 0) {
1497                     if (start >= textLength || text.charAt(start) != compiledPattern[i++]) {
1498                         pos.index = oldStart;
1499                         pos.errorIndex = start;
1500                         return null;
1501                     }
1502                     start++;
1503                 }
1504                 break;
1505 
1506             default:
1507                 // Peek the next pattern to determine if we need to
1508                 // obey the number of pattern letters for
1509                 // parsing. It's required when parsing contiguous
1510                 // digit text (e.g., "20010704") with a pattern which
1511                 // has no delimiters between fields, like "yyyyMMdd".
1512                 boolean obeyCount = false;
1513 
1514                 // In Arabic, a minus sign for a negative number is put after
1515                 // the number. Even in another locale, a minus sign can be
1516                 // put after a number using DateFormat.setNumberFormat().
1517                 // If both the minus sign and the field-delimiter are '-',
1518                 // subParse() needs to determine whether a '-' after a number
1519                 // in the given text is a delimiter or is a minus sign for the
1520                 // preceding number. We give subParse() a clue based on the
1521                 // information in compiledPattern.
1522                 boolean useFollowingMinusSignAsDelimiter = false;
1523 
1524                 if (i < compiledPattern.length) {
1525                     int nextTag = compiledPattern[i] >>> 8;
1526                     int nextCount = compiledPattern[i] & 0xff;
1527                     obeyCount = shouldObeyCount(nextTag, nextCount);
1528 
1529                     if (hasFollowingMinusSign &&
1530                         (nextTag == TAG_QUOTE_ASCII_CHAR ||
1531                          nextTag == TAG_QUOTE_CHARS)) {
1532 
1533                         if (nextTag != TAG_QUOTE_ASCII_CHAR) {
1534                             nextCount = compiledPattern[i+1];
1535                         }
1536 
1537                         if (nextCount == minusSign) {
1538                             useFollowingMinusSignAsDelimiter = true;
1539                         }
1540                     }
1541                 }
1542                 start = subParse(text, start, tag, count, obeyCount,
1543                                  ambiguousYear, pos,
1544                                  useFollowingMinusSignAsDelimiter, calb);
1545                 if (start < 0) {
1546                     pos.index = oldStart;
1547                     return null;
1548                 }
1549             }
1550         }
1551 
1552         // At this point the fields of Calendar have been set.  Calendar
1553         // will fill in default values for missing fields when the time
1554         // is computed.
1555 
1556         pos.index = start;
1557 
1558         Date parsedDate;
1559         try {
1560             parsedDate = calb.establish(calendar).getTime();
1561             // If the year value is ambiguous,
1562             // then the two-digit year == the default start year
1563             if (ambiguousYear[0]) {
1564                 if (parsedDate.before(defaultCenturyStart)) {
1565                     parsedDate = calb.addYear(100).establish(calendar).getTime();
1566                 }
1567             }
1568         }
1569         // An IllegalArgumentException will be thrown by Calendar.getTime()
1570         // if any fields are out of range, e.g., MONTH == 17.
1571         catch (IllegalArgumentException e) {
1572             pos.errorIndex = start;
1573             pos.index = oldStart;
1574             return null;
1575         }
1576 
1577         return parsedDate;
1578     }
1579 
1580     /* If the next tag/pattern is a <Numeric_Field> then the parser
1581      * should consider the count of digits while parsing the contigous digits
1582      * for the current tag/pattern
1583      */
1584     private boolean shouldObeyCount(int tag, int count) {
1585         switch (tag) {
1586             case PATTERN_MONTH:
1587             case PATTERN_MONTH_STANDALONE:
1588                 return count <= 2;
1589             case PATTERN_YEAR:
1590             case PATTERN_DAY_OF_MONTH:
1591             case PATTERN_HOUR_OF_DAY1:
1592             case PATTERN_HOUR_OF_DAY0:
1593             case PATTERN_MINUTE:
1594             case PATTERN_SECOND:
1595             case PATTERN_MILLISECOND:
1596             case PATTERN_DAY_OF_YEAR:
1597             case PATTERN_DAY_OF_WEEK_IN_MONTH:
1598             case PATTERN_WEEK_OF_YEAR:
1599             case PATTERN_WEEK_OF_MONTH:
1600             case PATTERN_HOUR1:
1601             case PATTERN_HOUR0:
1602             case PATTERN_WEEK_YEAR:
1603             case PATTERN_ISO_DAY_OF_WEEK:
1604                 return true;
1605             default:
1606                 return false;
1607         }
1608     }
1609 
1610     /**
1611      * Private code-size reduction function used by subParse.
1612      * @param text the time text being parsed.
1613      * @param start where to start parsing.
1614      * @param field the date field being parsed.
1615      * @param data the string array to parsed.
1616      * @return the new start position if matching succeeded; a negative number
1617      * indicating matching failure, otherwise.
1618      */
1619     private int matchString(String text, int start, int field, String[] data, CalendarBuilder calb)
1620     {
1621         int i = 0;
1622         int count = data.length;
1623 
1624         if (field == Calendar.DAY_OF_WEEK) {
1625             i = 1;
1626         }
1627 
1628         // There may be multiple strings in the data[] array which begin with
1629         // the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
1630         // We keep track of the longest match, and return that.  Note that this
1631         // unfortunately requires us to test all array elements.
1632         int bestMatchLength = 0, bestMatch = -1;
1633         for (; i<count; ++i)
1634         {
1635             int length = data[i].length();
1636             // Always compare if we have no match yet; otherwise only compare
1637             // against potentially better matches (longer strings).
1638             if (length > bestMatchLength &&
1639                 text.regionMatches(true, start, data[i], 0, length))
1640             {
1641                 bestMatch = i;
1642                 bestMatchLength = length;
1643             }
1644         }
1645         if (bestMatch >= 0)
1646         {
1647             calb.set(field, bestMatch);
1648             return start + bestMatchLength;
1649         }
1650         return -start;
1651     }
1652 
1653     /**
1654      * Performs the same thing as matchString(String, int, int,
1655      * String[]). This method takes a Map<String, Integer> instead of
1656      * String[].
1657      */
1658     private int matchString(String text, int start, int field,
1659                             Map<String,Integer> data, CalendarBuilder calb) {
1660         if (data != null) {
1661             // TODO: make this default when it's in the spec.
1662             if (data instanceof SortedMap) {
1663                 for (String name : data.keySet()) {
1664                     if (text.regionMatches(true, start, name, 0, name.length())) {
1665                         calb.set(field, data.get(name));
1666                         return start + name.length();
1667                     }
1668                 }
1669                 return -start;
1670             }
1671 
1672             String bestMatch = null;
1673 
1674             for (String name : data.keySet()) {
1675                 int length = name.length();
1676                 if (bestMatch == null || length > bestMatch.length()) {
1677                     if (text.regionMatches(true, start, name, 0, length)) {
1678                         bestMatch = name;
1679                     }
1680                 }
1681             }
1682 
1683             if (bestMatch != null) {
1684                 calb.set(field, data.get(bestMatch));
1685                 return start + bestMatch.length();
1686             }
1687         }
1688         return -start;
1689     }
1690 
1691     private int matchZoneString(String text, int start, String[] zoneNames) {
1692         for (int i = 1; i <= 4; ++i) {
1693             // Checking long and short zones [1 & 2],
1694             // and long and short daylight [3 & 4].
1695             String zoneName = zoneNames[i];
1696             if (zoneName.isEmpty()) {
1697                 // fill in by retrieving single name
1698                 zoneName = TimeZoneNameUtility.retrieveDisplayName(
1699                                 zoneNames[0], i >= 3, i % 2, locale);
1700                 zoneNames[i] = zoneName;
1701             }
1702             if (text.regionMatches(true, start,
1703                                    zoneName, 0, zoneName.length())) {
1704                 return i;
1705             }
1706         }
1707         return -1;
1708     }
1709 
1710     private boolean matchDSTString(String text, int start, int zoneIndex, int standardIndex,
1711                                    String[][] zoneStrings) {
1712         int index = standardIndex + 2;
1713         String zoneName  = zoneStrings[zoneIndex][index];
1714         if (text.regionMatches(true, start,
1715                                zoneName, 0, zoneName.length())) {
1716             return true;
1717         }
1718         return false;
1719     }
1720 
1721     /**
1722      * find time zone 'text' matched zoneStrings and set to internal
1723      * calendar.
1724      */
1725     private int subParseZoneString(String text, int start, CalendarBuilder calb) {
1726         boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
1727         TimeZone currentTimeZone = getTimeZone();
1728 
1729         // At this point, check for named time zones by looking through
1730         // the locale data from the TimeZoneNames strings.
1731         // Want to be able to parse both short and long forms.
1732         int zoneIndex = formatData.getZoneIndex(currentTimeZone.getID());
1733         TimeZone tz = null;
1734         String[][] zoneStrings = formatData.getZoneStringsWrapper();
1735         String[] zoneNames = null;
1736         int nameIndex = 0;
1737         if (zoneIndex != -1) {
1738             zoneNames = zoneStrings[zoneIndex];
1739             if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
1740                 if (nameIndex <= 2) {
1741                     // Check if the standard name (abbr) and the daylight name are the same.
1742                     useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
1743                 }
1744                 tz = TimeZone.getTimeZone(zoneNames[0]);
1745             }
1746         }
1747         if (tz == null) {
1748             zoneIndex = formatData.getZoneIndex(TimeZone.getDefault().getID());
1749             if (zoneIndex != -1) {
1750                 zoneNames = zoneStrings[zoneIndex];
1751                 if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
1752                     if (nameIndex <= 2) {
1753                         useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
1754                     }
1755                     tz = TimeZone.getTimeZone(zoneNames[0]);
1756                 }
1757             }
1758         }
1759 
1760         if (tz == null) {
1761             int len = zoneStrings.length;
1762             for (int i = 0; i < len; i++) {
1763                 zoneNames = zoneStrings[i];
1764                 if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
1765                     if (nameIndex <= 2) {
1766                         useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
1767                     }
1768                     tz = TimeZone.getTimeZone(zoneNames[0]);
1769                     break;
1770                 }
1771             }
1772         }
1773         if (tz != null) { // Matched any ?
1774             if (!tz.equals(currentTimeZone)) {
1775                 setTimeZone(tz);
1776             }
1777             // If the time zone matched uses the same name
1778             // (abbreviation) for both standard and daylight time,
1779             // let the time zone in the Calendar decide which one.
1780             //
1781             // Also if tz.getDSTSaving() returns 0 for DST, use tz to
1782             // determine the local time. (6645292)
1783             int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
1784             if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
1785                 calb.clear(Calendar.ZONE_OFFSET).set(Calendar.DST_OFFSET, dstAmount);
1786             }
1787             return (start + zoneNames[nameIndex].length());
1788         }
1789         return -start;
1790     }
1791 
1792     /**
1793      * Parses numeric forms of time zone offset, such as "hh:mm", and
1794      * sets calb to the parsed value.
1795      *
1796      * @param text  the text to be parsed
1797      * @param start the character position to start parsing
1798      * @param sign  1: positive; -1: negative
1799      * @param count 0: 'Z' or "GMT+hh:mm" parsing; 1 - 3: the number of 'X's
1800      * @param colon true - colon required between hh and mm; false - no colon required
1801      * @param calb  a CalendarBuilder in which the parsed value is stored
1802      * @return updated parsed position, or its negative value to indicate a parsing error
1803      */
1804     private int subParseNumericZone(String text, int start, int sign, int count,
1805                                     boolean colon, CalendarBuilder calb) {
1806         int index = start;
1807 
1808       parse:
1809         try {
1810             char c = text.charAt(index++);
1811             // Parse hh
1812             int hours;
1813             if (!isDigit(c)) {
1814                 break parse;
1815             }
1816             hours = c - '0';
1817             c = text.charAt(index++);
1818             if (isDigit(c)) {
1819                 hours = hours * 10 + (c - '0');
1820             } else {
1821                 // If no colon in RFC 822 or 'X' (ISO), two digits are
1822                 // required.
1823                 if (count > 0 || !colon) {
1824                     break parse;
1825                 }
1826                 --index;
1827             }
1828             if (hours > 23) {
1829                 break parse;
1830             }
1831             int minutes = 0;
1832             if (count != 1) {
1833                 // Proceed with parsing mm
1834                 c = text.charAt(index++);
1835                 if (colon) {
1836                     if (c != ':') {
1837                         break parse;
1838                     }
1839                     c = text.charAt(index++);
1840                 }
1841                 if (!isDigit(c)) {
1842                     break parse;
1843                 }
1844                 minutes = c - '0';
1845                 c = text.charAt(index++);
1846                 if (!isDigit(c)) {
1847                     break parse;
1848                 }
1849                 minutes = minutes * 10 + (c - '0');
1850                 if (minutes > 59) {
1851                     break parse;
1852                 }
1853             }
1854             minutes += hours * 60;
1855             calb.set(Calendar.ZONE_OFFSET, minutes * MILLIS_PER_MINUTE * sign)
1856                 .set(Calendar.DST_OFFSET, 0);
1857             return index;
1858         } catch (IndexOutOfBoundsException e) {
1859         }
1860         return  1 - index; // -(index - 1)
1861     }
1862 
1863     private boolean isDigit(char c) {
1864         return c >= '0' && c <= '9';
1865     }
1866 
1867     /**
1868      * Private member function that converts the parsed date strings into
1869      * timeFields. Returns -start (for ParsePosition) if failed.
1870      * @param text the time text to be parsed.
1871      * @param start where to start parsing.
1872      * @param patternCharIndex the index of the pattern character.
1873      * @param count the count of a pattern character.
1874      * @param obeyCount if true, then the next field directly abuts this one,
1875      * and we should use the count to know when to stop parsing.
1876      * @param ambiguousYear return parameter; upon return, if ambiguousYear[0]
1877      * is true, then a two-digit year was parsed and may need to be readjusted.
1878      * @param origPos origPos.errorIndex is used to return an error index
1879      * at which a parse error occurred, if matching failure occurs.
1880      * @return the new start position if matching succeeded; -1 indicating
1881      * matching failure, otherwise. In case matching failure occurred,
1882      * an error index is set to origPos.errorIndex.
1883      */
1884     private int subParse(String text, int start, int patternCharIndex, int count,
1885                          boolean obeyCount, boolean[] ambiguousYear,
1886                          ParsePosition origPos,
1887                          boolean useFollowingMinusSignAsDelimiter, CalendarBuilder calb) {
1888         Number number;
1889         int value = 0;
1890         ParsePosition pos = new ParsePosition(0);
1891         pos.index = start;
1892         if (patternCharIndex == PATTERN_WEEK_YEAR && !calendar.isWeekDateSupported()) {
1893             // use calendar year 'y' instead
1894             patternCharIndex = PATTERN_YEAR;
1895         }
1896         int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
1897 
1898         // If there are any spaces here, skip over them.  If we hit the end
1899         // of the string, then fail.
1900         for (;;) {
1901             if (pos.index >= text.length()) {
1902                 origPos.errorIndex = start;
1903                 return -1;
1904             }
1905             char c = text.charAt(pos.index);
1906             if (c != ' ' && c != '\t') {
1907                 break;
1908             }
1909             ++pos.index;
1910         }
1911         // Remember the actual start index
1912         int actualStart = pos.index;
1913 
1914       parsing:
1915         {
1916             // We handle a few special cases here where we need to parse
1917             // a number value.  We handle further, more generic cases below.  We need
1918             // to handle some of them here because some fields require extra processing on
1919             // the parsed value.
1920             if (patternCharIndex == PATTERN_HOUR_OF_DAY1 ||
1921                 patternCharIndex == PATTERN_HOUR1 ||
1922                 (patternCharIndex == PATTERN_MONTH && count <= 2) ||
1923                 (patternCharIndex == PATTERN_MONTH_STANDALONE && count <= 2) ||
1924                 patternCharIndex == PATTERN_YEAR ||
1925                 patternCharIndex == PATTERN_WEEK_YEAR) {
1926                 // It would be good to unify this with the obeyCount logic below,
1927                 // but that's going to be difficult.
1928                 if (obeyCount) {
1929                     if ((start+count) > text.length()) {
1930                         break parsing;
1931                     }
1932                     number = numberFormat.parse(text.substring(0, start+count), pos);
1933                 } else {
1934                     number = numberFormat.parse(text, pos);
1935                 }
1936                 if (number == null) {
1937                     if (patternCharIndex != PATTERN_YEAR || calendar instanceof GregorianCalendar) {
1938                         break parsing;
1939                     }
1940                 } else {
1941                     value = number.intValue();
1942 
1943                     if (useFollowingMinusSignAsDelimiter && (value < 0) &&
1944                         (((pos.index < text.length()) &&
1945                          (text.charAt(pos.index) != minusSign)) ||
1946                          ((pos.index == text.length()) &&
1947                           (text.charAt(pos.index-1) == minusSign)))) {
1948                         value = -value;
1949                         pos.index--;
1950                     }
1951                 }
1952             }
1953 
1954             boolean useDateFormatSymbols = useDateFormatSymbols();
1955 
1956             int index;
1957             switch (patternCharIndex) {
1958             case PATTERN_ERA: // 'G'
1959                 if (useDateFormatSymbols) {
1960                     if ((index = matchString(text, start, Calendar.ERA, formatData.getEras(), calb)) > 0) {
1961                         return index;
1962                     }
1963                 } else {
1964                     Map<String, Integer> map = getDisplayNamesMap(field, locale);
1965                     if ((index = matchString(text, start, field, map, calb)) > 0) {
1966                         return index;
1967                     }
1968                 }
1969                 break parsing;
1970 
1971             case PATTERN_WEEK_YEAR: // 'Y'
1972             case PATTERN_YEAR:      // 'y'
1973                 if (!(calendar instanceof GregorianCalendar)) {
1974                     // calendar might have text representations for year values,
1975                     // such as "\u5143" in JapaneseImperialCalendar.
1976                     int style = (count >= 4) ? Calendar.LONG : Calendar.SHORT;
1977                     Map<String, Integer> map = calendar.getDisplayNames(field, style, locale);
1978                     if (map != null) {
1979                         if ((index = matchString(text, start, field, map, calb)) > 0) {
1980                             return index;
1981                         }
1982                     }
1983                     calb.set(field, value);
1984                     return pos.index;
1985                 }
1986 
1987                 // If there are 3 or more YEAR pattern characters, this indicates
1988                 // that the year value is to be treated literally, without any
1989                 // two-digit year adjustments (e.g., from "01" to 2001).  Otherwise
1990                 // we made adjustments to place the 2-digit year in the proper
1991                 // century, for parsed strings from "00" to "99".  Any other string
1992                 // is treated literally:  "2250", "-1", "1", "002".
1993                 if (count <= 2 && (pos.index - actualStart) == 2
1994                     && Character.isDigit(text.charAt(actualStart))
1995                     && Character.isDigit(text.charAt(actualStart + 1))) {
1996                     // Assume for example that the defaultCenturyStart is 6/18/1903.
1997                     // This means that two-digit years will be forced into the range
1998                     // 6/18/1903 to 6/17/2003.  As a result, years 00, 01, and 02
1999                     // correspond to 2000, 2001, and 2002.  Years 04, 05, etc. correspond
2000                     // to 1904, 1905, etc.  If the year is 03, then it is 2003 if the
2001                     // other fields specify a date before 6/18, or 1903 if they specify a
2002                     // date afterwards.  As a result, 03 is an ambiguous year.  All other
2003                     // two-digit years are unambiguous.
2004                     int ambiguousTwoDigitYear = defaultCenturyStartYear % 100;
2005                     ambiguousYear[0] = value == ambiguousTwoDigitYear;
2006                     value += (defaultCenturyStartYear/100)*100 +
2007                         (value < ambiguousTwoDigitYear ? 100 : 0);
2008                 }
2009                 calb.set(field, value);
2010                 return pos.index;
2011 
2012             case PATTERN_MONTH: // 'M'
2013                 if (count <= 2) // i.e., M or MM.
2014                 {
2015                     // Don't want to parse the month if it is a string
2016                     // while pattern uses numeric style: M or MM.
2017                     // [We computed 'value' above.]
2018                     calb.set(Calendar.MONTH, value - 1);
2019                     return pos.index;
2020                 }
2021 
2022                 if (useDateFormatSymbols) {
2023                     // count >= 3 // i.e., MMM or MMMM
2024                     // Want to be able to parse both short and long forms.
2025                     // Try count == 4 first:
2026                     int newStart;
2027                     if ((newStart = matchString(text, start, Calendar.MONTH,
2028                                                 formatData.getMonths(), calb)) > 0) {
2029                         return newStart;
2030                     }
2031                     // count == 4 failed, now try count == 3
2032                     if ((index = matchString(text, start, Calendar.MONTH,
2033                                              formatData.getShortMonths(), calb)) > 0) {
2034                         return index;
2035                     }
2036                 } else {
2037                     Map<String, Integer> map = getDisplayContextNamesMap(field, locale);
2038                     if ((index = matchString(text, start, field, map, calb)) > 0) {
2039                         return index;
2040                     }
2041                 }
2042                 break parsing;
2043 
2044             case PATTERN_MONTH_STANDALONE: // 'L'
2045                 if (count <= 2) {
2046                     // Don't want to parse the month if it is a string
2047                     // while pattern uses numeric style: L or LL
2048                     //[we computed 'value' above.]
2049                     calb.set(Calendar.MONTH, value - 1);
2050                     return pos.index;
2051                 }
2052                 Map<String, Integer> maps = getDisplayNamesMap(field, locale);
2053                 if ((index = matchString(text, start, field, maps, calb)) > 0) {
2054                     return index;
2055                 }
2056                 break parsing;
2057 
2058             case PATTERN_HOUR_OF_DAY1: // 'k' 1-based.  eg, 23:59 + 1 hour =>> 24:59
2059                 if (!isLenient()) {
2060                     // Validate the hour value in non-lenient
2061                     if (value < 1 || value > 24) {
2062                         break parsing;
2063                     }
2064                 }
2065                 // [We computed 'value' above.]
2066                 if (value == calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1) {
2067                     value = 0;
2068                 }
2069                 calb.set(Calendar.HOUR_OF_DAY, value);
2070                 return pos.index;
2071 
2072             case PATTERN_DAY_OF_WEEK:  // 'E'
2073                 {
2074                     if (useDateFormatSymbols) {
2075                         // Want to be able to parse both short and long forms.
2076                         // Try count == 4 (DDDD) first:
2077                         int newStart;
2078                         if ((newStart=matchString(text, start, Calendar.DAY_OF_WEEK,
2079                                                   formatData.getWeekdays(), calb)) > 0) {
2080                             return newStart;
2081                         }
2082                         // DDDD failed, now try DDD
2083                         if ((index = matchString(text, start, Calendar.DAY_OF_WEEK,
2084                                                  formatData.getShortWeekdays(), calb)) > 0) {
2085                             return index;
2086                         }
2087                     } else {
2088                         int[] styles = { Calendar.LONG, Calendar.SHORT };
2089                         for (int style : styles) {
2090                             Map<String,Integer> map = calendar.getDisplayNames(field, style, locale);
2091                             if ((index = matchString(text, start, field, map, calb)) > 0) {
2092                                 return index;
2093                             }
2094                         }
2095                     }
2096                 }
2097                 break parsing;
2098 
2099             case PATTERN_AM_PM:    // 'a'
2100                 if (useDateFormatSymbols) {
2101                     if ((index = matchString(text, start, Calendar.AM_PM,
2102                                              formatData.getAmPmStrings(), calb)) > 0) {
2103                         return index;
2104                     }
2105                 } else {
2106                     Map<String,Integer> map = getDisplayNamesMap(field, locale);
2107                     if ((index = matchString(text, start, field, map, calb)) > 0) {
2108                         return index;
2109                     }
2110                 }
2111                 break parsing;
2112 
2113             case PATTERN_HOUR1: // 'h' 1-based.  eg, 11PM + 1 hour =>> 12 AM
2114                 if (!isLenient()) {
2115                     // Validate the hour value in non-lenient
2116                     if (value < 1 || value > 12) {
2117                         break parsing;
2118                     }
2119                 }
2120                 // [We computed 'value' above.]
2121                 if (value == calendar.getLeastMaximum(Calendar.HOUR) + 1) {
2122                     value = 0;
2123                 }
2124                 calb.set(Calendar.HOUR, value);
2125                 return pos.index;
2126 
2127             case PATTERN_ZONE_NAME:  // 'z'
2128             case PATTERN_ZONE_VALUE: // 'Z'
2129                 {
2130                     int sign = 0;
2131                     try {
2132                         char c = text.charAt(pos.index);
2133                         if (c == '+') {
2134                             sign = 1;
2135                         } else if (c == '-') {
2136                             sign = -1;
2137                         }
2138                         if (sign == 0) {
2139                             // Try parsing a custom time zone "GMT+hh:mm" or "GMT".
2140                             if ((c == 'G' || c == 'g')
2141                                 && (text.length() - start) >= GMT.length()
2142                                 && text.regionMatches(true, start, GMT, 0, GMT.length())) {
2143                                 pos.index = start + GMT.length();
2144 
2145                                 if ((text.length() - pos.index) > 0) {
2146                                     c = text.charAt(pos.index);
2147                                     if (c == '+') {
2148                                         sign = 1;
2149                                     } else if (c == '-') {
2150                                         sign = -1;
2151                                     }
2152                                 }
2153 
2154                                 if (sign == 0) {    /* "GMT" without offset */
2155                                     calb.set(Calendar.ZONE_OFFSET, 0)
2156                                         .set(Calendar.DST_OFFSET, 0);
2157                                     return pos.index;
2158                                 }
2159 
2160                                 // Parse the rest as "hh:mm"
2161                                 int i = subParseNumericZone(text, ++pos.index,
2162                                                             sign, 0, true, calb);
2163                                 if (i > 0) {
2164                                     return i;
2165                                 }
2166                                 pos.index = -i;
2167                             } else {
2168                                 // Try parsing the text as a time zone
2169                                 // name or abbreviation.
2170                                 int i = subParseZoneString(text, pos.index, calb);
2171                                 if (i > 0) {
2172                                     return i;
2173                                 }
2174                                 pos.index = -i;
2175                             }
2176                         } else {
2177                             // Parse the rest as "hhmm" (RFC 822)
2178                             int i = subParseNumericZone(text, ++pos.index,
2179                                                         sign, 0, false, calb);
2180                             if (i > 0) {
2181                                 return i;
2182                             }
2183                             pos.index = -i;
2184                         }
2185                     } catch (IndexOutOfBoundsException e) {
2186                     }
2187                 }
2188                 break parsing;
2189 
2190             case PATTERN_ISO_ZONE:   // 'X'
2191                 {
2192                     if ((text.length() - pos.index) <= 0) {
2193                         break parsing;
2194                     }
2195 
2196                     int sign;
2197                     char c = text.charAt(pos.index);
2198                     if (c == 'Z') {
2199                         calb.set(Calendar.ZONE_OFFSET, 0).set(Calendar.DST_OFFSET, 0);
2200                         return ++pos.index;
2201                     }
2202 
2203                     // parse text as "+/-hh[[:]mm]" based on count
2204                     if (c == '+') {
2205                         sign = 1;
2206                     } else if (c == '-') {
2207                         sign = -1;
2208                     } else {
2209                         ++pos.index;
2210                         break parsing;
2211                     }
2212                     int i = subParseNumericZone(text, ++pos.index, sign, count,
2213                                                 count == 3, calb);
2214                     if (i > 0) {
2215                         return i;
2216                     }
2217                     pos.index = -i;
2218                 }
2219                 break parsing;
2220 
2221             default:
2222          // case PATTERN_DAY_OF_MONTH:         // 'd'
2223          // case PATTERN_HOUR_OF_DAY0:         // 'H' 0-based.  eg, 23:59 + 1 hour =>> 00:59
2224          // case PATTERN_MINUTE:               // 'm'
2225          // case PATTERN_SECOND:               // 's'
2226          // case PATTERN_MILLISECOND:          // 'S'
2227          // case PATTERN_DAY_OF_YEAR:          // 'D'
2228          // case PATTERN_DAY_OF_WEEK_IN_MONTH: // 'F'
2229          // case PATTERN_WEEK_OF_YEAR:         // 'w'
2230          // case PATTERN_WEEK_OF_MONTH:        // 'W'
2231          // case PATTERN_HOUR0:                // 'K' 0-based.  eg, 11PM + 1 hour =>> 0 AM
2232          // case PATTERN_ISO_DAY_OF_WEEK:      // 'u' (pseudo field);
2233 
2234                 // Handle "generic" fields
2235                 if (obeyCount) {
2236                     if ((start+count) > text.length()) {
2237                         break parsing;
2238                     }
2239                     number = numberFormat.parse(text.substring(0, start+count), pos);
2240                 } else {
2241                     number = numberFormat.parse(text, pos);
2242                 }
2243                 if (number != null) {
2244                     value = number.intValue();
2245 
2246                     if (useFollowingMinusSignAsDelimiter && (value < 0) &&
2247                         (((pos.index < text.length()) &&
2248                          (text.charAt(pos.index) != minusSign)) ||
2249                          ((pos.index == text.length()) &&
2250                           (text.charAt(pos.index-1) == minusSign)))) {
2251                         value = -value;
2252                         pos.index--;
2253                     }
2254 
2255                     calb.set(field, value);
2256                     return pos.index;
2257                 }
2258                 break parsing;
2259             }
2260         }
2261 
2262         // Parsing failed.
2263         origPos.errorIndex = pos.index;
2264         return -1;
2265     }
2266 
2267     /**
2268      * Returns true if the DateFormatSymbols has been set explicitly or locale
2269      * is null.
2270      */
2271     private boolean useDateFormatSymbols() {
2272         return useDateFormatSymbols || locale == null;
2273     }
2274 
2275     /**
2276      * Translates a pattern, mapping each character in the from string to the
2277      * corresponding character in the to string.
2278      *
2279      * @exception IllegalArgumentException if the given pattern is invalid
2280      */
2281     private String translatePattern(String pattern, String from, String to) {
2282         StringBuilder result = new StringBuilder();
2283         boolean inQuote = false;
2284         for (int i = 0; i < pattern.length(); ++i) {
2285             char c = pattern.charAt(i);
2286             if (inQuote) {
2287                 if (c == '\'') {
2288                     inQuote = false;
2289                 }
2290             }
2291             else {
2292                 if (c == '\'') {
2293                     inQuote = true;
2294                 } else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
2295                     int ci = from.indexOf(c);
2296                     if (ci >= 0) {
2297                         // patternChars is longer than localPatternChars due
2298                         // to serialization compatibility. The pattern letters
2299                         // unsupported by localPatternChars pass through.
2300                         if (ci < to.length()) {
2301                             c = to.charAt(ci);
2302                         }
2303                     } else {
2304                         throw new IllegalArgumentException("Illegal pattern " +
2305                                                            " character '" +
2306                                                            c + "'");
2307                     }
2308                 }
2309             }
2310             result.append(c);
2311         }
2312         if (inQuote) {
2313             throw new IllegalArgumentException("Unfinished quote in pattern");
2314         }
2315         return result.toString();
2316     }
2317 
2318     /**
2319      * Returns a pattern string describing this date format.
2320      *
2321      * @return a pattern string describing this date format.
2322      */
2323     public String toPattern() {
2324         return pattern;
2325     }
2326 
2327     /**
2328      * Returns a localized pattern string describing this date format.
2329      *
2330      * @return a localized pattern string describing this date format.
2331      */
2332     public String toLocalizedPattern() {
2333         return translatePattern(pattern,
2334                                 DateFormatSymbols.patternChars,
2335                                 formatData.getLocalPatternChars());
2336     }
2337 
2338     /**
2339      * Applies the given pattern string to this date format.
2340      *
2341      * @param pattern the new date and time pattern for this date format
2342      * @exception NullPointerException if the given pattern is null
2343      * @exception IllegalArgumentException if the given pattern is invalid
2344      */
2345     public void applyPattern(String pattern)
2346     {
2347         applyPatternImpl(pattern);
2348     }
2349 
2350     private void applyPatternImpl(String pattern) {
2351         compiledPattern = compile(pattern);
2352         this.pattern = pattern;
2353     }
2354 
2355     /**
2356      * Applies the given localized pattern string to this date format.
2357      *
2358      * @param pattern a String to be mapped to the new date and time format
2359      *        pattern for this format
2360      * @exception NullPointerException if the given pattern is null
2361      * @exception IllegalArgumentException if the given pattern is invalid
2362      */
2363     public void applyLocalizedPattern(String pattern) {
2364          String p = translatePattern(pattern,
2365                                      formatData.getLocalPatternChars(),
2366                                      DateFormatSymbols.patternChars);
2367          compiledPattern = compile(p);
2368          this.pattern = p;
2369     }
2370 
2371     /**
2372      * Gets a copy of the date and time format symbols of this date format.
2373      *
2374      * @return the date and time format symbols of this date format
2375      * @see #setDateFormatSymbols
2376      */
2377     public DateFormatSymbols getDateFormatSymbols()
2378     {
2379         return (DateFormatSymbols)formatData.clone();
2380     }
2381 
2382     /**
2383      * Sets the date and time format symbols of this date format.
2384      *
2385      * @param newFormatSymbols the new date and time format symbols
2386      * @exception NullPointerException if the given newFormatSymbols is null
2387      * @see #getDateFormatSymbols
2388      */
2389     public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols)
2390     {
2391         this.formatData = (DateFormatSymbols)newFormatSymbols.clone();
2392         useDateFormatSymbols = true;
2393     }
2394 
2395     /**
2396      * Creates a copy of this <code>SimpleDateFormat</code>. This also
2397      * clones the format's date format symbols.
2398      *
2399      * @return a clone of this <code>SimpleDateFormat</code>
2400      */
2401     @Override
2402     public Object clone() {
2403         SimpleDateFormat other = (SimpleDateFormat) super.clone();
2404         other.formatData = (DateFormatSymbols) formatData.clone();
2405         return other;
2406     }
2407 
2408     /**
2409      * Returns the hash code value for this <code>SimpleDateFormat</code> object.
2410      *
2411      * @return the hash code value for this <code>SimpleDateFormat</code> object.
2412      */
2413     @Override
2414     public int hashCode()
2415     {
2416         return pattern.hashCode();
2417         // just enough fields for a reasonable distribution
2418     }
2419 
2420     /**
2421      * Compares the given object with this <code>SimpleDateFormat</code> for
2422      * equality.
2423      *
2424      * @return true if the given object is equal to this
2425      * <code>SimpleDateFormat</code>
2426      */
2427     @Override
2428     public boolean equals(Object obj)
2429     {
2430         if (!super.equals(obj)) {
2431             return false; // super does class check
2432         }
2433         SimpleDateFormat that = (SimpleDateFormat) obj;
2434         return (pattern.equals(that.pattern)
2435                 && formatData.equals(that.formatData));
2436     }
2437 
2438     private static final int[] REST_OF_STYLES = {
2439         Calendar.SHORT_STANDALONE, Calendar.LONG_FORMAT, Calendar.LONG_STANDALONE,
2440     };
2441     private Map<String, Integer> getDisplayNamesMap(int field, Locale locale) {
2442         Map<String, Integer> map = calendar.getDisplayNames(field, Calendar.SHORT_FORMAT, locale);
2443         // Get all SHORT and LONG styles (avoid NARROW styles).
2444         for (int style : REST_OF_STYLES) {
2445             Map<String, Integer> m = calendar.getDisplayNames(field, style, locale);
2446             if (m != null) {
2447                 map.putAll(m);
2448             }
2449         }
2450         return map;
2451     }
2452 
2453     /**
2454      * Obtains display names map, taking the context into account. Currently only
2455      * the month name pattern 'M' is context dependent.
2456      */
2457     private Map<String, Integer> getDisplayContextNamesMap(int field, Locale locale) {
2458         Map<String, Integer> map = calendar.getDisplayNames(field,
2459             forceStandaloneForm ? Calendar.SHORT_STANDALONE : Calendar.SHORT_FORMAT, locale);
2460         // Get the LONG style
2461         Map<String, Integer> m = calendar.getDisplayNames(field,
2462             forceStandaloneForm ? Calendar.LONG_STANDALONE : Calendar.LONG_FORMAT, locale);
2463         if (m != null) {
2464             map.putAll(m);
2465         }
2466         return map;
2467     }
2468 
2469     /**
2470      * After reading an object from the input stream, the format
2471      * pattern in the object is verified.
2472      *
2473      * @exception InvalidObjectException if the pattern is invalid
2474      */
2475     @java.io.Serial
2476     private void readObject(ObjectInputStream stream)
2477                          throws IOException, ClassNotFoundException {
2478         stream.defaultReadObject();
2479 
2480         try {
2481             compiledPattern = compile(pattern);
2482         } catch (Exception e) {
2483             throw new InvalidObjectException("invalid pattern");
2484         }
2485 
2486         if (serialVersionOnStream < 1) {
2487             // didn't have defaultCenturyStart field
2488             initializeDefaultCentury();
2489         }
2490         else {
2491             // fill in dependent transient field
2492             parseAmbiguousDatesAsAfter(defaultCenturyStart);
2493         }
2494         serialVersionOnStream = currentSerialVersion;
2495 
2496         // If the deserialized object has a SimpleTimeZone, try
2497         // to replace it with a ZoneInfo equivalent in order to
2498         // be compatible with the SimpleTimeZone-based
2499         // implementation as much as possible.
2500         TimeZone tz = getTimeZone();
2501         if (tz instanceof SimpleTimeZone) {
2502             String id = tz.getID();
2503             TimeZone zi = TimeZone.getTimeZone(id);
2504             if (zi != null && zi.hasSameRules(tz) && zi.getID().equals(id)) {
2505                 setTimeZone(zi);
2506             }
2507         }
2508     }
2509 
2510     /**
2511      * Analyze the negative subpattern of DecimalFormat and set/update values
2512      * as necessary.
2513      */
2514     private void checkNegativeNumberExpression() {
2515         if ((numberFormat instanceof DecimalFormat) &&
2516             !numberFormat.equals(originalNumberFormat)) {
2517             String numberPattern = ((DecimalFormat)numberFormat).toPattern();
2518             if (!numberPattern.equals(originalNumberPattern)) {
2519                 hasFollowingMinusSign = false;
2520 
2521                 int separatorIndex = numberPattern.indexOf(';');
2522                 // If the negative subpattern is not absent, we have to analayze
2523                 // it in order to check if it has a following minus sign.
2524                 if (separatorIndex > -1) {
2525                     int minusIndex = numberPattern.indexOf('-', separatorIndex);
2526                     if ((minusIndex > numberPattern.lastIndexOf('0')) &&
2527                         (minusIndex > numberPattern.lastIndexOf('#'))) {
2528                         hasFollowingMinusSign = true;
2529                         minusSign = ((DecimalFormat)numberFormat).getDecimalFormatSymbols().getMinusSign();
2530                     }
2531                 }
2532                 originalNumberPattern = numberPattern;
2533             }
2534             originalNumberFormat = numberFormat;
2535         }
2536     }
2537 
2538 }