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