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