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