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