2 * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
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.
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).
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.
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
27 * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
28 * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
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.
41 import java.io.IOException;
42 import java.io.InvalidObjectException;
43 import java.io.ObjectInputStream;
44 import java.util.Calendar;
45 import java.util.Date;
46 import java.util.Locale;
48 import java.util.MissingResourceException;
49 import java.util.ResourceBundle;
50 import java.util.SimpleTimeZone;
51 import java.util.TimeZone;
52 import java.util.concurrent.ConcurrentHashMap;
53 import java.util.concurrent.ConcurrentMap;
55 import static java.text.DateFormatSymbols.*;
58 * <code>SimpleDateFormat</code> is a concrete class for formatting and
59 * parsing dates in a locale-sensitive manner. It allows for formatting
60 * (date -> text), parsing (text -> date), and normalization.
63 * <code>SimpleDateFormat</code> allows you to start by choosing
64 * any user-defined patterns for date-time formatting. However, you
65 * are encouraged to create a date-time formatter with either
66 * <code>getTimeInstance</code>, <code>getDateInstance</code>, or
67 * <code>getDateTimeInstance</code> in <code>DateFormat</code>. Each
68 * of these class methods can return a date/time formatter initialized
69 * with a default format pattern. You may modify the format pattern
70 * using the <code>applyPattern</code> methods as desired.
71 * For more information on using these methods, see
74 * <h4>Date and Time Patterns</h4>
76 * Date and time formats are specified by <em>date and time pattern</em>
78 * Within date and time pattern strings, unquoted letters from
79 * <code>'A'</code> to <code>'Z'</code> and from <code>'a'</code> to
80 * <code>'z'</code> are interpreted as pattern letters representing the
81 * components of a date or time string.
82 * Text can be quoted using single quotes (<code>'</code>) to avoid
84 * <code>"''"</code> represents a single quote.
85 * All other characters are not interpreted; they're simply copied into the
86 * output string during formatting or matched against the input string
89 * The following pattern letters are defined (all other characters from
90 * <code>'A'</code> to <code>'Z'</code> and from <code>'a'</code> to
91 * <code>'z'</code> are reserved):
93 * <table border=0 cellspacing=3 cellpadding=0 summary="Chart shows pattern letters, date/time component, presentation, and examples.">
94 * <tr bgcolor="#ccccff">
95 * <th align=left>Letter
96 * <th align=left>Date or Time Component
97 * <th align=left>Presentation
98 * <th align=left>Examples
102 * <td><a href="#text">Text</a>
103 * <td><code>AD</code>
104 * <tr bgcolor="#eeeeff">
107 * <td><a href="#year">Year</a>
108 * <td><code>1996</code>; <code>96</code>
112 * <td><a href="#year">Year</a>
113 * <td><code>2009</code>; <code>09</code>
114 * <tr bgcolor="#eeeeff">
117 * <td><a href="#month">Month</a>
118 * <td><code>July</code>; <code>Jul</code>; <code>07</code>
122 * <td><a href="#number">Number</a>
123 * <td><code>27</code>
124 * <tr bgcolor="#eeeeff">
127 * <td><a href="#number">Number</a>
132 * <td><a href="#number">Number</a>
133 * <td><code>189</code>
134 * <tr bgcolor="#eeeeff">
137 * <td><a href="#number">Number</a>
138 * <td><code>10</code>
141 * <td>Day of week in month
142 * <td><a href="#number">Number</a>
144 * <tr bgcolor="#eeeeff">
146 * <td>Day name in week
147 * <td><a href="#text">Text</a>
148 * <td><code>Tuesday</code>; <code>Tue</code>
151 * <td>Day number of week (1 = Monday, ..., 7 = Sunday)
152 * <td><a href="#number">Number</a>
154 * <tr bgcolor="#eeeeff">
157 * <td><a href="#text">Text</a>
158 * <td><code>PM</code>
161 * <td>Hour in day (0-23)
162 * <td><a href="#number">Number</a>
164 * <tr bgcolor="#eeeeff">
166 * <td>Hour in day (1-24)
167 * <td><a href="#number">Number</a>
168 * <td><code>24</code>
171 * <td>Hour in am/pm (0-11)
172 * <td><a href="#number">Number</a>
174 * <tr bgcolor="#eeeeff">
176 * <td>Hour in am/pm (1-12)
177 * <td><a href="#number">Number</a>
178 * <td><code>12</code>
182 * <td><a href="#number">Number</a>
183 * <td><code>30</code>
184 * <tr bgcolor="#eeeeff">
186 * <td>Second in minute
187 * <td><a href="#number">Number</a>
188 * <td><code>55</code>
192 * <td><a href="#number">Number</a>
193 * <td><code>978</code>
194 * <tr bgcolor="#eeeeff">
197 * <td><a href="#timezone">General time zone</a>
198 * <td><code>Pacific Standard Time</code>; <code>PST</code>; <code>GMT-08:00</code>
202 * <td><a href="#rfc822timezone">RFC 822 time zone</a>
203 * <td><code>-0800</code>
204 * <tr bgcolor="#eeeeff">
207 * <td><a href="#iso8601timezone">ISO 8601 time zone</a>
208 * <td><code>-08</code>; <code>-0800</code>; <code>-08:00</code>
211 * Pattern letters are usually repeated, as their number determines the
212 * exact presentation:
214 * <li><strong><a name="text">Text:</a></strong>
215 * For formatting, if the number of pattern letters is 4 or more,
216 * the full form is used; otherwise a short or abbreviated form
217 * is used if available.
218 * For parsing, both forms are accepted, independent of the number
219 * of pattern letters.<br><br></li>
220 * <li><strong><a name="number">Number:</a></strong>
221 * For formatting, the number of pattern letters is the minimum
222 * number of digits, and shorter numbers are zero-padded to this amount.
223 * For parsing, the number of pattern letters is ignored unless
224 * it's needed to separate two adjacent fields.<br><br></li>
225 * <li><strong><a name="year">Year:</a></strong>
226 * If the formatter's {@link #getCalendar() Calendar} is the Gregorian
227 * calendar, the following rules are applied.<br>
229 * <li>For formatting, if the number of pattern letters is 2, the year
230 * is truncated to 2 digits; otherwise it is interpreted as a
231 * <a href="#number">number</a>.
232 * <li>For parsing, if the number of pattern letters is more than 2,
233 * the year is interpreted literally, regardless of the number of
234 * digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to
236 * <li>For parsing with the abbreviated year pattern ("y" or "yy"),
237 * <code>SimpleDateFormat</code> must interpret the abbreviated year
238 * relative to some century. It does this by adjusting dates to be
239 * within 80 years before and 20 years after the time the <code>SimpleDateFormat</code>
240 * instance is created. For example, using a pattern of "MM/dd/yy" and a
241 * <code>SimpleDateFormat</code> instance created on Jan 1, 1997, the string
242 * "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64"
243 * would be interpreted as May 4, 1964.
244 * During parsing, only strings consisting of exactly two digits, as defined by
245 * {@link Character#isDigit(char)}, will be parsed into the default century.
246 * Any other numeric string, such as a one digit string, a three or more digit
247 * string, or a two digit string that isn't all digits (for example, "-1"), is
248 * interpreted literally. So "01/02/3" or "01/02/003" are parsed, using the
249 * same pattern, as Jan 2, 3 AD. Likewise, "01/02/-3" is parsed as Jan 2, 4 BC.
251 * Otherwise, calendar system specific forms are applied.
252 * For both formatting and parsing, if the number of pattern
253 * letters is 4 or more, a calendar specific {@linkplain
254 * Calendar#LONG long form} is used. Otherwise, a calendar
255 * specific {@linkplain Calendar#SHORT short or abbreviated form}
258 * If week year {@code 'Y'} is specified and the {@linkplain
259 * #getCalendar() calendar} doesn't support any <a
260 * href="../util/GregorianCalendar.html#week_year"> week
261 * years</a>, the calendar year ({@code 'y'}) is used instead. The
262 * support of week years can be tested with a call to {@link
263 * DateFormat#getCalendar() getCalendar()}.{@link
264 * java.util.Calendar#isWeekDateSupported()
265 * isWeekDateSupported()}.<br><br></li>
266 * <li><strong><a name="month">Month:</a></strong>
267 * If the number of pattern letters is 3 or more, the month is
268 * interpreted as <a href="#text">text</a>; otherwise,
269 * it is interpreted as a <a href="#number">number</a>.<br><br></li>
270 * <li><strong><a name="timezone">General time zone:</a></strong>
271 * Time zones are interpreted as <a href="#text">text</a> if they have
272 * names. For time zones representing a GMT offset value, the
273 * following syntax is used:
275 * <a name="GMTOffsetTimeZone"><i>GMTOffsetTimeZone:</i></a>
276 * <code>GMT</code> <i>Sign</i> <i>Hours</i> <code>:</code> <i>Minutes</i>
277 * <i>Sign:</i> one of
281 * <i>Digit</i> <i>Digit</i>
283 * <i>Digit</i> <i>Digit</i>
284 * <i>Digit:</i> one of
285 * <code>0 1 2 3 4 5 6 7 8 9</code></pre>
286 * <i>Hours</i> must be between 0 and 23, and <i>Minutes</i> must be between
287 * 00 and 59. The format is locale independent and digits must be taken
288 * from the Basic Latin block of the Unicode standard.
289 * <p>For parsing, <a href="#rfc822timezone">RFC 822 time zones</a> are also
290 * accepted.<br><br></li>
291 * <li><strong><a name="rfc822timezone">RFC 822 time zone:</a></strong>
292 * For formatting, the RFC 822 4-digit time zone format is used:
295 * <i>RFC822TimeZone:</i>
296 * <i>Sign</i> <i>TwoDigitHours</i> <i>Minutes</i>
297 * <i>TwoDigitHours:</i>
298 * <i>Digit Digit</i></pre>
299 * <i>TwoDigitHours</i> must be between 00 and 23. Other definitions
300 * are as for <a href="#timezone">general time zones</a>.
302 * <p>For parsing, <a href="#timezone">general time zones</a> are also
304 * <li><strong><a name="iso8601timezone">ISO 8601 Time zone:</a></strong>
305 * The number of pattern letters designates the format for both formatting
306 * and parsing as follows:
308 * <i>ISO8601TimeZone:</i>
309 * <i>OneLetterISO8601TimeZone</i>
310 * <i>TwoLetterISO8601TimeZone</i>
311 * <i>ThreeLetterISO8601TimeZone</i>
312 * <i>OneLetterISO8601TimeZone:</i>
313 * <i>Sign</i> <i>TwoDigitHours</i>
315 * <i>TwoLetterISO8601TimeZone:</i>
316 * <i>Sign</i> <i>TwoDigitHours</i> <i>Minutes</i>
318 * <i>ThreeLetterISO8601TimeZone:</i>
319 * <i>Sign</i> <i>TwoDigitHours</i> {@code :} <i>Minutes</i>
321 * Other definitions are as for <a href="#timezone">general time zones</a> or
322 * <a href="#rfc822timezone">RFC 822 time zones</a>.
324 * <p>For formatting, if the offset value from GMT is 0, {@code "Z"} is
325 * produced. If the number of pattern letters is 1, any fraction of an hour
326 * is ignored. For example, if the pattern is {@code "X"} and the time zone is
327 * {@code "GMT+05:30"}, {@code "+05"} is produced.
329 * <p>For parsing, {@code "Z"} is parsed as the UTC time zone designator.
330 * <a href="#timezone">General time zones</a> are <em>not</em> accepted.
332 * <p>If the number of pattern letters is 4 or more, {@link
333 * IllegalArgumentException} is thrown when constructing a {@code
334 * SimpleDateFormat} or {@linkplain #applyPattern(String) applying a
337 * <code>SimpleDateFormat</code> also supports <em>localized date and time
338 * pattern</em> strings. In these strings, the pattern letters described above
339 * may be replaced with other, locale dependent, pattern letters.
340 * <code>SimpleDateFormat</code> does not deal with the localization of text
341 * other than the pattern letters; that's up to the client of the class.
346 * The following examples show how date and time patterns are interpreted in
347 * the U.S. locale. The given date and time are 2001-07-04 12:08:56 local time
348 * in the U.S. Pacific Time time zone.
350 * <table border=0 cellspacing=3 cellpadding=0 summary="Examples of date and time patterns interpreted in the U.S. locale">
351 * <tr bgcolor="#ccccff">
352 * <th align=left>Date and Time Pattern
353 * <th align=left>Result
355 * <td><code>"yyyy.MM.dd G 'at' HH:mm:ss z"</code>
356 * <td><code>2001.07.04 AD at 12:08:56 PDT</code>
357 * <tr bgcolor="#eeeeff">
358 * <td><code>"EEE, MMM d, ''yy"</code>
359 * <td><code>Wed, Jul 4, '01</code>
361 * <td><code>"h:mm a"</code>
362 * <td><code>12:08 PM</code>
363 * <tr bgcolor="#eeeeff">
364 * <td><code>"hh 'o''clock' a, zzzz"</code>
365 * <td><code>12 o'clock PM, Pacific Daylight Time</code>
367 * <td><code>"K:mm a, z"</code>
368 * <td><code>0:08 PM, PDT</code>
369 * <tr bgcolor="#eeeeff">
370 * <td><code>"yyyyy.MMMMM.dd GGG hh:mm aaa"</code>
371 * <td><code>02001.July.04 AD 12:08 PM</code>
373 * <td><code>"EEE, d MMM yyyy HH:mm:ss Z"</code>
374 * <td><code>Wed, 4 Jul 2001 12:08:56 -0700</code>
375 * <tr bgcolor="#eeeeff">
376 * <td><code>"yyMMddHHmmssZ"</code>
377 * <td><code>010704120856-0700</code>
379 * <td><code>"yyyy-MM-dd'T'HH:mm:ss.SSSZ"</code>
380 * <td><code>2001-07-04T12:08:56.235-0700</code>
381 * <tr bgcolor="#eeeeff">
382 * <td><code>"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"</code>
383 * <td><code>2001-07-04T12:08:56.235-07:00</code>
385 * <td><code>"YYYY-'W'ww-u"</code>
386 * <td><code>2001-W27-3</code>
390 * <h4><a name="synchronization">Synchronization</a></h4>
393 * Date formats are not synchronized.
394 * It is recommended to create separate format instances for each thread.
395 * If multiple threads access a format concurrently, it must be synchronized
398 * @see <a href="http://java.sun.com/docs/books/tutorial/i18n/format/simpleDateFormat.html">Java Tutorial</a>
399 * @see java.util.Calendar
400 * @see java.util.TimeZone
402 * @see DateFormatSymbols
403 * @author Mark Davis, Chen-Lieh Huang, Alan Liu
405 public class SimpleDateFormat extends DateFormat {
407 // the official serial version ID which says cryptically
408 // which version we're compatible with
409 static final long serialVersionUID = 4774881970558875024L;
411 // the internal serial version which says which version was written
412 // - 0 (default) for version up to JDK 1.1.3
413 // - 1 for version from JDK 1.1.4, which includes a new field
414 static final int currentSerialVersion = 1;
417 * The version of the serialized data on the stream. Possible values:
419 * <li><b>0</b> or not present on stream: JDK 1.1.3. This version
420 * has no <code>defaultCenturyStart</code> on stream.
421 * <li><b>1</b> JDK 1.1.4 or later. This version adds
422 * <code>defaultCenturyStart</code>.
424 * When streaming out this class, the most recent format
425 * and the highest allowable <code>serialVersionOnStream</code>
430 private int serialVersionOnStream = currentSerialVersion;
433 * The pattern string of this formatter. This is always a non-localized
434 * pattern. May not be null. See class documentation for details.
437 private String pattern;
440 * Saved numberFormat and pattern.
441 * @see SimpleDateFormat#checkNegativeNumberExpression
443 transient private NumberFormat originalNumberFormat;
444 transient private String originalNumberPattern;
447 * The minus sign to be used with format and parse.
449 transient private char minusSign = '-';
452 * True when a negative sign follows a number.
453 * (True as default in Arabic.)
455 transient private boolean hasFollowingMinusSign = false;
458 * The compiled pattern.
460 transient private char[] compiledPattern;
463 * Tags for the compiled pattern.
465 private final static int TAG_QUOTE_ASCII_CHAR = 100;
466 private final static int TAG_QUOTE_CHARS = 101;
469 * Locale dependent digit zero.
470 * @see #zeroPaddingNumber
471 * @see java.text.DecimalFormatSymbols#getZeroDigit
473 transient private char zeroDigit;
476 * The symbols used by this formatter for week names, month names,
477 * etc. May not be null.
479 * @see java.text.DateFormatSymbols
481 private DateFormatSymbols formatData;
484 * We map dates with two-digit years into the century starting at
485 * <code>defaultCenturyStart</code>, which may be any date. May
490 private Date defaultCenturyStart;
492 transient private int defaultCenturyStartYear;
494 private static final int MILLIS_PER_MINUTE = 60 * 1000;
496 // For time zones that have no names, use strings GMT+minutes and
497 // GMT-minutes. For instance, in France the time zone is GMT+60.
498 private static final String GMT = "GMT";
501 * Cache to hold the DateTimePatterns of a Locale.
503 private static final ConcurrentMap<Locale, String[]> cachedLocaleData
504 = new ConcurrentHashMap<Locale, String[]>(3);
507 * Cache NumberFormat instances with Locale key.
509 private static final ConcurrentMap<Locale, NumberFormat> cachedNumberFormatData
510 = new ConcurrentHashMap<Locale, NumberFormat>(3);
513 * The Locale used to instantiate this
514 * <code>SimpleDateFormat</code>. The value may be null if this object
515 * has been created by an older <code>SimpleDateFormat</code> and
521 private Locale locale;
524 * Indicates whether this <code>SimpleDateFormat</code> should use
525 * the DateFormatSymbols. If true, the format and parse methods
526 * use the DateFormatSymbols values. If false, the format and
527 * parse methods call Calendar.getDisplayName or
528 * Calendar.getDisplayNames.
530 transient boolean useDateFormatSymbols;
533 * Constructs a <code>SimpleDateFormat</code> using the default pattern and
534 * date format symbols for the default locale.
535 * <b>Note:</b> This constructor may not support all locales.
536 * For full coverage, use the factory methods in the {@link DateFormat}
539 public SimpleDateFormat() {
540 this(SHORT, SHORT, Locale.getDefault(Locale.Category.FORMAT));
544 * Constructs a <code>SimpleDateFormat</code> using the given pattern and
545 * the default date format symbols for the default locale.
546 * <b>Note:</b> This constructor may not support all locales.
547 * For full coverage, use the factory methods in the {@link DateFormat}
550 * @param pattern the pattern describing the date and time format
551 * @exception NullPointerException if the given pattern is null
552 * @exception IllegalArgumentException if the given pattern is invalid
554 public SimpleDateFormat(String pattern)
556 this(pattern, Locale.getDefault(Locale.Category.FORMAT));
560 * Constructs a <code>SimpleDateFormat</code> using the given pattern and
561 * the default date format symbols for the given locale.
562 * <b>Note:</b> This constructor may not support all locales.
563 * For full coverage, use the factory methods in the {@link DateFormat}
566 * @param pattern the pattern describing the date and time format
567 * @param locale the locale whose date format symbols should be used
568 * @exception NullPointerException if the given pattern or locale is null
569 * @exception IllegalArgumentException if the given pattern is invalid
571 public SimpleDateFormat(String pattern, Locale locale)
573 if (pattern == null || locale == null) {
574 throw new NullPointerException();
577 initializeCalendar(locale);
578 this.pattern = pattern;
579 this.formatData = DateFormatSymbols.getInstanceRef(locale);
580 this.locale = locale;
585 * Constructs a <code>SimpleDateFormat</code> using the given pattern and
586 * date format symbols.
588 * @param pattern the pattern describing the date and time format
589 * @param formatSymbols the date format symbols to be used for formatting
590 * @exception NullPointerException if the given pattern or formatSymbols is null
591 * @exception IllegalArgumentException if the given pattern is invalid
593 public SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)
595 if (pattern == null || formatSymbols == null) {
596 throw new NullPointerException();
599 this.pattern = pattern;
600 this.formatData = (DateFormatSymbols) formatSymbols.clone();
601 this.locale = Locale.getDefault(Locale.Category.FORMAT);
602 initializeCalendar(this.locale);
603 initialize(this.locale);
604 useDateFormatSymbols = true;
607 /* Package-private, called by DateFormat factory methods */
608 SimpleDateFormat(int timeStyle, int dateStyle, Locale loc) {
610 throw new NullPointerException();
614 // initialize calendar and related fields
615 initializeCalendar(loc);
617 /* try the cache first */
618 String[] dateTimePatterns = cachedLocaleData.get(loc);
619 if (dateTimePatterns == null) { /* cache miss */
620 ResourceBundle r = null; // LocaleData.getDateFormatData(loc);
621 if (!isGregorianCalendar()) {
623 dateTimePatterns = r.getStringArray(getCalendarName() + ".DateTimePatterns");
624 } catch (MissingResourceException e) {
627 if (dateTimePatterns == null) {
628 dateTimePatterns = r.getStringArray("DateTimePatterns");
631 cachedLocaleData.putIfAbsent(loc, dateTimePatterns);
633 formatData = DateFormatSymbols.getInstanceRef(loc);
634 if ((timeStyle >= 0) && (dateStyle >= 0)) {
635 Object[] dateTimeArgs = {dateTimePatterns[timeStyle],
636 dateTimePatterns[dateStyle + 4]};
637 pattern = MessageFormat.format(dateTimePatterns[8], dateTimeArgs);
639 else if (timeStyle >= 0) {
640 pattern = dateTimePatterns[timeStyle];
642 else if (dateStyle >= 0) {
643 pattern = dateTimePatterns[dateStyle + 4];
646 throw new IllegalArgumentException("No date or time style specified");
652 /* Initialize compiledPattern and numberFormat fields */
653 private void initialize(Locale loc) {
654 // Verify and compile the given pattern.
655 compiledPattern = compile(pattern);
657 /* try the cache first */
658 numberFormat = cachedNumberFormatData.get(loc);
659 if (numberFormat == null) { /* cache miss */
660 numberFormat = NumberFormat.getIntegerInstance(loc);
661 numberFormat.setGroupingUsed(false);
664 cachedNumberFormatData.putIfAbsent(loc, numberFormat);
666 numberFormat = (NumberFormat) numberFormat.clone();
668 initializeDefaultCentury();
671 private void initializeCalendar(Locale loc) {
672 if (calendar == null) {
674 // The format object must be constructed using the symbols for this zone.
675 // However, the calendar should use the current default TimeZone.
676 // If this is not contained in the locale zone strings, then the zone
677 // will be formatted using generic GMT+/-H:MM nomenclature.
678 calendar = Calendar.getInstance(TimeZone.getDefault(), loc);
683 * Returns the compiled form of the given pattern. The syntax of
684 * the compiled pattern is:
704 * TAG_QUOTE_ASCII_CHAR ascii_char
708 * where `short_length' is an 8-bit unsigned integer between 0 and
709 * 254. `long_length' is a sequence of an 8-bit integer 255 and a
710 * 32-bit signed integer value which is split into upper and lower
711 * 16-bit fields in two char's. `pattern_char_index' is an 8-bit
712 * integer between 0 and 18. `ascii_char' is an 7-bit ASCII
713 * character value. `data' depends on its Tag value.
715 * If Length is short_length, Tag and short_length are packed in a
716 * single char, as illustrated below.
718 * char[0] = (Tag << 8) | short_length;
721 * If Length is long_length, Tag and 255 are packed in the first
722 * char and a 32-bit integer, as illustrated below.
724 * char[0] = (Tag << 8) | 255;
725 * char[1] = (char) (long_length >>> 16);
726 * char[2] = (char) (long_length & 0xffff);
729 * If Tag is a pattern_char_index, its Length is the number of
730 * pattern characters. For example, if the given pattern is
731 * "yyyy", Tag is 1 and Length is 4, followed by no data.
733 * If Tag is TAG_QUOTE_CHARS, its Length is the number of char's
734 * following the TagField. For example, if the given pattern is
735 * "'o''clock'", Length is 7 followed by a char sequence of
736 * <code>o&nbs;'&nbs;c&nbs;l&nbs;o&nbs;c&nbs;k</code>.
738 * TAG_QUOTE_ASCII_CHAR is a special tag and has an ASCII
739 * character in place of Length. For example, if the given pattern
740 * is "'o'", the TaggedData entry is
741 * <code>((TAG_QUOTE_ASCII_CHAR&nbs;<<&nbs;8)&nbs;|&nbs;'o')</code>.
743 * @exception NullPointerException if the given pattern is null
744 * @exception IllegalArgumentException if the given pattern is invalid
746 private char[] compile(String pattern) {
747 int length = pattern.length();
748 boolean inQuote = false;
749 StringBuilder compiledPattern = new StringBuilder(length * 2);
750 StringBuilder tmpBuffer = null;
754 for (int i = 0; i < length; i++) {
755 char c = pattern.charAt(i);
758 // '' is treated as a single quote regardless of being
759 // in a quoted section.
760 if ((i + 1) < length) {
761 c = pattern.charAt(i + 1);
765 encode(lastTag, count, compiledPattern);
772 compiledPattern.append((char)(TAG_QUOTE_ASCII_CHAR << 8 | c));
779 encode(lastTag, count, compiledPattern);
783 if (tmpBuffer == null) {
784 tmpBuffer = new StringBuilder(length);
786 tmpBuffer.setLength(0);
790 int len = tmpBuffer.length();
792 char ch = tmpBuffer.charAt(0);
794 compiledPattern.append((char)(TAG_QUOTE_ASCII_CHAR << 8 | ch));
796 compiledPattern.append((char)(TAG_QUOTE_CHARS << 8 | 1));
797 compiledPattern.append(ch);
800 encode(TAG_QUOTE_CHARS, len, compiledPattern);
801 compiledPattern.append(tmpBuffer);
811 if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
813 encode(lastTag, count, compiledPattern);
818 // In most cases, c would be a delimiter, such as ':'.
819 compiledPattern.append((char)(TAG_QUOTE_ASCII_CHAR << 8 | c));
821 // Take any contiguous non-ASCII alphabet characters and
822 // put them in a single TAG_QUOTE_CHARS.
824 for (j = i + 1; j < length; j++) {
825 char d = pattern.charAt(j);
826 if (d == '\'' || (d >= 'a' && d <= 'z' || d >= 'A' && d <= 'Z')) {
830 compiledPattern.append((char)(TAG_QUOTE_CHARS << 8 | (j - i)));
832 compiledPattern.append(pattern.charAt(i));
840 if ((tag = DateFormatSymbols.patternChars.indexOf(c)) == -1) {
841 throw new IllegalArgumentException("Illegal pattern character " +
844 if (lastTag == -1 || lastTag == tag) {
849 encode(lastTag, count, compiledPattern);
855 throw new IllegalArgumentException("Unterminated quote");
859 encode(lastTag, count, compiledPattern);
862 // Copy the compiled pattern to a char array
863 int len = compiledPattern.length();
864 char[] r = new char[len];
865 compiledPattern.getChars(0, len, r, 0);
870 * Encodes the given tag and length and puts encoded char(s) into buffer.
872 private static final void encode(int tag, int length, StringBuilder buffer) {
873 if (tag == PATTERN_ISO_ZONE && length >= 4) {
874 throw new IllegalArgumentException("invalid ISO 8601 format: length=" + length);
877 buffer.append((char)(tag << 8 | length));
879 buffer.append((char)((tag << 8) | 0xff));
880 buffer.append((char)(length >>> 16));
881 buffer.append((char)(length & 0xffff));
885 /* Initialize the fields we use to disambiguate ambiguous years. Separate
886 * so we can call it from readObject().
888 private void initializeDefaultCentury() {
889 calendar.setTimeInMillis(System.currentTimeMillis());
890 calendar.add( Calendar.YEAR, -80 );
891 parseAmbiguousDatesAsAfter(calendar.getTime());
894 /* Define one-century window into which to disambiguate dates using
897 private void parseAmbiguousDatesAsAfter(Date startDate) {
898 defaultCenturyStart = startDate;
899 calendar.setTime(startDate);
900 defaultCenturyStartYear = calendar.get(Calendar.YEAR);
904 * Sets the 100-year period 2-digit years will be interpreted as being in
905 * to begin on the date the user specifies.
907 * @param startDate During parsing, two digit years will be placed in the range
908 * <code>startDate</code> to <code>startDate + 100 years</code>.
909 * @see #get2DigitYearStart
912 public void set2DigitYearStart(Date startDate) {
913 parseAmbiguousDatesAsAfter(new Date(startDate.getTime()));
917 * Returns the beginning date of the 100-year period 2-digit years are interpreted
920 * @return the start of the 100-year period into which two digit years are
922 * @see #set2DigitYearStart
925 public Date get2DigitYearStart() {
926 return (Date) defaultCenturyStart.clone();
930 * Formats the given <code>Date</code> into a date/time string and appends
931 * the result to the given <code>StringBuffer</code>.
933 * @param date the date-time value to be formatted into a date-time string.
934 * @param toAppendTo where the new date-time text is to be appended.
935 * @param pos the formatting position. On input: an alignment field,
936 * if desired. On output: the offsets of the alignment field.
937 * @return the formatted date-time string.
938 * @exception NullPointerException if the given {@code date} is {@code null}.
940 public StringBuffer format(Date date, StringBuffer toAppendTo,
943 pos.beginIndex = pos.endIndex = 0;
944 return format(date, toAppendTo, pos.getFieldDelegate());
947 // Called from Format after creating a FieldDelegate
948 private StringBuffer format(Date date, StringBuffer toAppendTo,
949 FieldDelegate delegate) {
950 // Convert input date to time field list
951 calendar.setTime(date);
953 boolean useDateFormatSymbols = useDateFormatSymbols();
955 for (int i = 0; i < compiledPattern.length; ) {
956 int tag = compiledPattern[i] >>> 8;
957 int count = compiledPattern[i++] & 0xff;
959 count = compiledPattern[i++] << 16;
960 count |= compiledPattern[i++];
964 case TAG_QUOTE_ASCII_CHAR:
965 toAppendTo.append((char)count);
968 case TAG_QUOTE_CHARS:
969 toAppendTo.append(compiledPattern, i, count);
974 subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
982 * Formats an Object producing an <code>AttributedCharacterIterator</code>.
983 * You can use the returned <code>AttributedCharacterIterator</code>
984 * to build the resulting String, as well as to determine information
985 * about the resulting String.
987 * Each attribute key of the AttributedCharacterIterator will be of type
988 * <code>DateFormat.Field</code>, with the corresponding attribute value
989 * being the same as the attribute key.
991 * @exception NullPointerException if obj is null.
992 * @exception IllegalArgumentException if the Format cannot format the
993 * given object, or if the Format's pattern string is invalid.
994 * @param obj The object to format
995 * @return AttributedCharacterIterator describing the formatted value.
998 public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
999 StringBuffer sb = new StringBuffer();
1000 CharacterIteratorFieldDelegate delegate = new
1001 CharacterIteratorFieldDelegate();
1003 if (obj instanceof Date) {
1004 format((Date)obj, sb, delegate);
1006 else if (obj instanceof Number) {
1007 format(new Date(((Number)obj).longValue()), sb, delegate);
1009 else if (obj == null) {
1010 throw new NullPointerException(
1011 "formatToCharacterIterator must be passed non-null object");
1014 throw new IllegalArgumentException(
1015 "Cannot format given Object as a Date");
1017 return delegate.getIterator(sb.toString());
1020 // Map index into pattern character string to Calendar field number
1021 private static final int[] PATTERN_INDEX_TO_CALENDAR_FIELD =
1023 Calendar.ERA, Calendar.YEAR, Calendar.MONTH, Calendar.DATE,
1024 Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY, Calendar.MINUTE,
1025 Calendar.SECOND, Calendar.MILLISECOND, Calendar.DAY_OF_WEEK,
1026 Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK_IN_MONTH,
1027 Calendar.WEEK_OF_YEAR, Calendar.WEEK_OF_MONTH,
1028 Calendar.AM_PM, Calendar.HOUR, Calendar.HOUR, Calendar.ZONE_OFFSET,
1029 Calendar.ZONE_OFFSET,
1030 // Pseudo Calendar fields
1031 CalendarBuilder.WEEK_YEAR,
1032 CalendarBuilder.ISO_DAY_OF_WEEK,
1033 Calendar.ZONE_OFFSET
1036 // Map index into pattern character string to DateFormat field number
1037 private static final int[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD = {
1038 DateFormat.ERA_FIELD, DateFormat.YEAR_FIELD, DateFormat.MONTH_FIELD,
1039 DateFormat.DATE_FIELD, DateFormat.HOUR_OF_DAY1_FIELD,
1040 DateFormat.HOUR_OF_DAY0_FIELD, DateFormat.MINUTE_FIELD,
1041 DateFormat.SECOND_FIELD, DateFormat.MILLISECOND_FIELD,
1042 DateFormat.DAY_OF_WEEK_FIELD, DateFormat.DAY_OF_YEAR_FIELD,
1043 DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD, DateFormat.WEEK_OF_YEAR_FIELD,
1044 DateFormat.WEEK_OF_MONTH_FIELD, DateFormat.AM_PM_FIELD,
1045 DateFormat.HOUR1_FIELD, DateFormat.HOUR0_FIELD,
1046 DateFormat.TIMEZONE_FIELD, DateFormat.TIMEZONE_FIELD,
1047 DateFormat.YEAR_FIELD, DateFormat.DAY_OF_WEEK_FIELD,
1048 DateFormat.TIMEZONE_FIELD
1051 // Maps from DecimalFormatSymbols index to Field constant
1052 private static final Field[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID = {
1053 Field.ERA, Field.YEAR, Field.MONTH, Field.DAY_OF_MONTH,
1054 Field.HOUR_OF_DAY1, Field.HOUR_OF_DAY0, Field.MINUTE,
1055 Field.SECOND, Field.MILLISECOND, Field.DAY_OF_WEEK,
1056 Field.DAY_OF_YEAR, Field.DAY_OF_WEEK_IN_MONTH,
1057 Field.WEEK_OF_YEAR, Field.WEEK_OF_MONTH,
1058 Field.AM_PM, Field.HOUR1, Field.HOUR0, Field.TIME_ZONE,
1060 Field.YEAR, Field.DAY_OF_WEEK,
1065 * Private member function that does the real date/time formatting.
1067 private void subFormat(int patternCharIndex, int count,
1068 FieldDelegate delegate, StringBuffer buffer,
1069 boolean useDateFormatSymbols)
1071 int maxIntCount = Integer.MAX_VALUE;
1072 String current = null;
1073 int beginOffset = buffer.length();
1075 int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
1077 if (field == CalendarBuilder.WEEK_YEAR) {
1078 if (calendar.isWeekDateSupported()) {
1079 value = calendar.getWeekYear();
1081 // use calendar year 'y' instead
1082 patternCharIndex = PATTERN_YEAR;
1083 field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
1084 value = calendar.get(field);
1086 } else if (field == CalendarBuilder.ISO_DAY_OF_WEEK) {
1087 value = CalendarBuilder.toISODayOfWeek(calendar.get(Calendar.DAY_OF_WEEK));
1089 value = calendar.get(field);
1092 int style = (count >= 4) ? Calendar.LONG : Calendar.SHORT;
1093 if (!useDateFormatSymbols && field != CalendarBuilder.ISO_DAY_OF_WEEK) {
1094 current = calendar.getDisplayName(field, style, locale);
1097 // Note: zeroPaddingNumber() assumes that maxDigits is either
1098 // 2 or maxIntCount. If we make any changes to this,
1099 // zeroPaddingNumber() must be fixed.
1101 switch (patternCharIndex) {
1102 case PATTERN_ERA: // 'G'
1103 if (useDateFormatSymbols) {
1104 String[] eras = formatData.getEras();
1105 if (value < eras.length)
1106 current = eras[value];
1108 if (current == null)
1112 case PATTERN_WEEK_YEAR: // 'Y'
1113 case PATTERN_YEAR: // 'y'
1114 if (calendar instanceof GregorianCalendar) {
1116 zeroPaddingNumber(value, count, maxIntCount, buffer);
1118 zeroPaddingNumber(value, 2, 2, buffer); // clip 1996 to 96
1120 if (current == null) {
1121 zeroPaddingNumber(value, style == Calendar.LONG ? 1 : count,
1122 maxIntCount, buffer);
1127 case PATTERN_MONTH: // 'M'
1128 if (useDateFormatSymbols) {
1131 months = formatData.getMonths();
1132 current = months[value];
1133 } else if (count == 3) {
1134 months = formatData.getShortMonths();
1135 current = months[value];
1142 if (current == null) {
1143 zeroPaddingNumber(value+1, count, maxIntCount, buffer);
1147 case PATTERN_HOUR_OF_DAY1: // 'k' 1-based. eg, 23:59 + 1 hour =>> 24:59
1148 if (current == null) {
1150 zeroPaddingNumber(calendar.getMaximum(Calendar.HOUR_OF_DAY)+1,
1151 count, maxIntCount, buffer);
1153 zeroPaddingNumber(value, count, maxIntCount, buffer);
1157 case PATTERN_DAY_OF_WEEK: // 'E'
1158 if (useDateFormatSymbols) {
1161 weekdays = formatData.getWeekdays();
1162 current = weekdays[value];
1163 } else { // count < 4, use abbreviated form if exists
1164 weekdays = formatData.getShortWeekdays();
1165 current = weekdays[value];
1170 case PATTERN_AM_PM: // 'a'
1171 if (useDateFormatSymbols) {
1172 String[] ampm = formatData.getAmPmStrings();
1173 current = ampm[value];
1177 case PATTERN_HOUR1: // 'h' 1-based. eg, 11PM + 1 hour =>> 12 AM
1178 if (current == null) {
1180 zeroPaddingNumber(calendar.getLeastMaximum(Calendar.HOUR)+1,
1181 count, maxIntCount, buffer);
1183 zeroPaddingNumber(value, count, maxIntCount, buffer);
1187 case PATTERN_ZONE_NAME: // 'z'
1188 if (current == null) {
1189 if (formatData.locale == null || formatData.isZoneStringsSet) {
1191 formatData.getZoneIndex(calendar.getTimeZone().getID());
1192 if (zoneIndex == -1) {
1193 value = calendar.get(Calendar.ZONE_OFFSET) +
1194 calendar.get(Calendar.DST_OFFSET);
1195 // buffer.append(ZoneInfoFile.toCustomID(value));
1197 int index = (calendar.get(Calendar.DST_OFFSET) == 0) ? 1: 3;
1199 // Use the short name
1202 String[][] zoneStrings = formatData.getZoneStringsWrapper();
1203 buffer.append(zoneStrings[zoneIndex][index]);
1206 TimeZone tz = calendar.getTimeZone();
1207 boolean daylight = (calendar.get(Calendar.DST_OFFSET) != 0);
1208 int tzstyle = (count < 4 ? TimeZone.SHORT : TimeZone.LONG);
1209 buffer.append(tz.getDisplayName(daylight, tzstyle, formatData.locale));
1214 case PATTERN_ZONE_VALUE: // 'Z' ("-/+hhmm" form)
1215 value = (calendar.get(Calendar.ZONE_OFFSET) +
1216 calendar.get(Calendar.DST_OFFSET)) / 60000;
1225 int num = (value / 60) * 100 + (value % 60);
1226 // CalendarUtils.sprintf0d(buffer, num, width);
1229 case PATTERN_ISO_ZONE: // 'X'
1230 value = calendar.get(Calendar.ZONE_OFFSET)
1231 + calendar.get(Calendar.DST_OFFSET);
1246 // CalendarUtils.sprintf0d(buffer, value / 60, 2);
1254 // CalendarUtils.sprintf0d(buffer, value % 60, 2);
1258 // case PATTERN_DAY_OF_MONTH: // 'd'
1259 // case PATTERN_HOUR_OF_DAY0: // 'H' 0-based. eg, 23:59 + 1 hour =>> 00:59
1260 // case PATTERN_MINUTE: // 'm'
1261 // case PATTERN_SECOND: // 's'
1262 // case PATTERN_MILLISECOND: // 'S'
1263 // case PATTERN_DAY_OF_YEAR: // 'D'
1264 // case PATTERN_DAY_OF_WEEK_IN_MONTH: // 'F'
1265 // case PATTERN_WEEK_OF_YEAR: // 'w'
1266 // case PATTERN_WEEK_OF_MONTH: // 'W'
1267 // case PATTERN_HOUR0: // 'K' eg, 11PM + 1 hour =>> 0 AM
1268 // case PATTERN_ISO_DAY_OF_WEEK: // 'u' pseudo field, Monday = 1, ..., Sunday = 7
1269 if (current == null) {
1270 zeroPaddingNumber(value, count, maxIntCount, buffer);
1273 } // switch (patternCharIndex)
1275 if (current != null) {
1276 buffer.append(current);
1279 int fieldID = PATTERN_INDEX_TO_DATE_FORMAT_FIELD[patternCharIndex];
1280 Field f = PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID[patternCharIndex];
1282 delegate.formatted(fieldID, f, f, beginOffset, buffer.length(), buffer);
1286 * Formats a number with the specified minimum and maximum number of digits.
1288 private final void zeroPaddingNumber(int value, int minDigits, int maxDigits, StringBuffer buffer)
1290 // Optimization for 1, 2 and 4 digit numbers. This should
1291 // cover most cases of formatting date/time related items.
1292 // Note: This optimization code assumes that maxDigits is
1293 // either 2 or Integer.MAX_VALUE (maxIntCount in format()).
1295 if (zeroDigit == 0) {
1296 zeroDigit = ((DecimalFormat)numberFormat).getDecimalFormatSymbols().getZeroDigit();
1299 if (value < 100 && minDigits >= 1 && minDigits <= 2) {
1301 if (minDigits == 2) {
1302 buffer.append(zeroDigit);
1304 buffer.append((char)(zeroDigit + value));
1306 buffer.append((char)(zeroDigit + value / 10));
1307 buffer.append((char)(zeroDigit + value % 10));
1310 } else if (value >= 1000 && value < 10000) {
1311 if (minDigits == 4) {
1312 buffer.append((char)(zeroDigit + value / 1000));
1314 buffer.append((char)(zeroDigit + value / 100));
1316 buffer.append((char)(zeroDigit + value / 10));
1317 buffer.append((char)(zeroDigit + value % 10));
1320 if (minDigits == 2 && maxDigits == 2) {
1321 zeroPaddingNumber(value % 100, 2, 2, buffer);
1326 } catch (Exception e) {
1329 numberFormat.setMinimumIntegerDigits(minDigits);
1330 numberFormat.setMaximumIntegerDigits(maxDigits);
1331 numberFormat.format((long)value, buffer, DontCareFieldPosition.INSTANCE);
1336 * Parses text from a string to produce a <code>Date</code>.
1338 * The method attempts to parse text starting at the index given by
1340 * If parsing succeeds, then the index of <code>pos</code> is updated
1341 * to the index after the last character used (parsing does not necessarily
1342 * use all characters up to the end of the string), and the parsed
1343 * date is returned. The updated <code>pos</code> can be used to
1344 * indicate the starting point for the next call to this method.
1345 * If an error occurs, then the index of <code>pos</code> is not
1346 * changed, the error index of <code>pos</code> is set to the index of
1347 * the character where the error occurred, and null is returned.
1349 * <p>This parsing operation uses the {@link DateFormat#calendar
1350 * calendar} to produce a {@code Date}. All of the {@code
1351 * calendar}'s date-time fields are {@linkplain Calendar#clear()
1352 * cleared} before parsing, and the {@code calendar}'s default
1353 * values of the date-time fields are used for any missing
1354 * date-time information. For example, the year value of the
1355 * parsed {@code Date} is 1970 with {@link GregorianCalendar} if
1356 * no year value is given from the parsing operation. The {@code
1357 * TimeZone} value may be overwritten, depending on the given
1358 * pattern and the time zone value in {@code text}. Any {@code
1359 * TimeZone} value that has previously been set by a call to
1360 * {@link #setTimeZone(java.util.TimeZone) setTimeZone} may need
1361 * to be restored for further operations.
1363 * @param text A <code>String</code>, part of which should be parsed.
1364 * @param pos A <code>ParsePosition</code> object with index and error
1365 * index information as described above.
1366 * @return A <code>Date</code> parsed from the string. In case of
1367 * error, returns null.
1368 * @exception NullPointerException if <code>text</code> or <code>pos</code> is null.
1370 public Date parse(String text, ParsePosition pos)
1372 checkNegativeNumberExpression();
1374 int start = pos.index;
1375 int oldStart = start;
1376 int textLength = text.length();
1378 boolean[] ambiguousYear = {false};
1380 CalendarBuilder calb = new CalendarBuilder();
1382 for (int i = 0; i < compiledPattern.length; ) {
1383 int tag = compiledPattern[i] >>> 8;
1384 int count = compiledPattern[i++] & 0xff;
1386 count = compiledPattern[i++] << 16;
1387 count |= compiledPattern[i++];
1391 case TAG_QUOTE_ASCII_CHAR:
1392 if (start >= textLength || text.charAt(start) != (char)count) {
1393 pos.index = oldStart;
1394 pos.errorIndex = start;
1400 case TAG_QUOTE_CHARS:
1401 while (count-- > 0) {
1402 if (start >= textLength || text.charAt(start) != compiledPattern[i++]) {
1403 pos.index = oldStart;
1404 pos.errorIndex = start;
1412 // Peek the next pattern to determine if we need to
1413 // obey the number of pattern letters for
1414 // parsing. It's required when parsing contiguous
1415 // digit text (e.g., "20010704") with a pattern which
1416 // has no delimiters between fields, like "yyyyMMdd".
1417 boolean obeyCount = false;
1419 // In Arabic, a minus sign for a negative number is put after
1420 // the number. Even in another locale, a minus sign can be
1421 // put after a number using DateFormat.setNumberFormat().
1422 // If both the minus sign and the field-delimiter are '-',
1423 // subParse() needs to determine whether a '-' after a number
1424 // in the given text is a delimiter or is a minus sign for the
1425 // preceding number. We give subParse() a clue based on the
1426 // information in compiledPattern.
1427 boolean useFollowingMinusSignAsDelimiter = false;
1429 if (i < compiledPattern.length) {
1430 int nextTag = compiledPattern[i] >>> 8;
1431 if (!(nextTag == TAG_QUOTE_ASCII_CHAR ||
1432 nextTag == TAG_QUOTE_CHARS)) {
1436 if (hasFollowingMinusSign &&
1437 (nextTag == TAG_QUOTE_ASCII_CHAR ||
1438 nextTag == TAG_QUOTE_CHARS)) {
1440 if (nextTag == TAG_QUOTE_ASCII_CHAR) {
1441 c = compiledPattern[i] & 0xff;
1443 c = compiledPattern[i+1];
1446 if (c == minusSign) {
1447 useFollowingMinusSignAsDelimiter = true;
1451 start = subParse(text, start, tag, count, obeyCount,
1453 useFollowingMinusSignAsDelimiter, calb);
1455 pos.index = oldStart;
1461 // At this point the fields of Calendar have been set. Calendar
1462 // will fill in default values for missing fields when the time
1469 parsedDate = calb.establish(calendar).getTime();
1470 // If the year value is ambiguous,
1471 // then the two-digit year == the default start year
1472 if (ambiguousYear[0]) {
1473 if (parsedDate.before(defaultCenturyStart)) {
1474 parsedDate = calb.addYear(100).establish(calendar).getTime();
1478 // An IllegalArgumentException will be thrown by Calendar.getTime()
1479 // if any fields are out of range, e.g., MONTH == 17.
1480 catch (IllegalArgumentException e) {
1481 pos.errorIndex = start;
1482 pos.index = oldStart;
1490 * Private code-size reduction function used by subParse.
1491 * @param text the time text being parsed.
1492 * @param start where to start parsing.
1493 * @param field the date field being parsed.
1494 * @param data the string array to parsed.
1495 * @return the new start position if matching succeeded; a negative number
1496 * indicating matching failure, otherwise.
1498 private int matchString(String text, int start, int field, String[] data, CalendarBuilder calb)
1501 int count = data.length;
1503 if (field == Calendar.DAY_OF_WEEK) i = 1;
1505 // There may be multiple strings in the data[] array which begin with
1506 // the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
1507 // We keep track of the longest match, and return that. Note that this
1508 // unfortunately requires us to test all array elements.
1509 int bestMatchLength = 0, bestMatch = -1;
1510 for (; i<count; ++i)
1512 int length = data[i].length();
1513 // Always compare if we have no match yet; otherwise only compare
1514 // against potentially better matches (longer strings).
1515 if (length > bestMatchLength &&
1516 text.regionMatches(true, start, data[i], 0, length))
1519 bestMatchLength = length;
1524 calb.set(field, bestMatch);
1525 return start + bestMatchLength;
1531 * Performs the same thing as matchString(String, int, int,
1532 * String[]). This method takes a Map<String, Integer> instead of
1535 private int matchString(String text, int start, int field,
1536 Map<String,Integer> data, CalendarBuilder calb) {
1538 String bestMatch = null;
1540 for (String name : data.keySet()) {
1541 int length = name.length();
1542 if (bestMatch == null || length > bestMatch.length()) {
1543 if (text.regionMatches(true, start, name, 0, length)) {
1549 if (bestMatch != null) {
1550 calb.set(field, data.get(bestMatch));
1551 return start + bestMatch.length();
1557 private int matchZoneString(String text, int start, String[] zoneNames) {
1558 for (int i = 1; i <= 4; ++i) {
1559 // Checking long and short zones [1 & 2],
1560 // and long and short daylight [3 & 4].
1561 String zoneName = zoneNames[i];
1562 if (text.regionMatches(true, start,
1563 zoneName, 0, zoneName.length())) {
1570 private boolean matchDSTString(String text, int start, int zoneIndex, int standardIndex,
1571 String[][] zoneStrings) {
1572 int index = standardIndex + 2;
1573 String zoneName = zoneStrings[zoneIndex][index];
1574 if (text.regionMatches(true, start,
1575 zoneName, 0, zoneName.length())) {
1582 * find time zone 'text' matched zoneStrings and set to internal
1585 private int subParseZoneString(String text, int start, CalendarBuilder calb) {
1586 boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
1587 TimeZone currentTimeZone = getTimeZone();
1589 // At this point, check for named time zones by looking through
1590 // the locale data from the TimeZoneNames strings.
1591 // Want to be able to parse both short and long forms.
1592 int zoneIndex = formatData.getZoneIndex(currentTimeZone.getID());
1594 String[][] zoneStrings = formatData.getZoneStringsWrapper();
1595 String[] zoneNames = null;
1597 if (zoneIndex != -1) {
1598 zoneNames = zoneStrings[zoneIndex];
1599 if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
1600 if (nameIndex <= 2) {
1601 // Check if the standard name (abbr) and the daylight name are the same.
1602 useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
1604 tz = TimeZone.getTimeZone(zoneNames[0]);
1608 zoneIndex = formatData.getZoneIndex(TimeZone.getDefault().getID());
1609 if (zoneIndex != -1) {
1610 zoneNames = zoneStrings[zoneIndex];
1611 if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
1612 if (nameIndex <= 2) {
1613 useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
1615 tz = TimeZone.getTimeZone(zoneNames[0]);
1621 int len = zoneStrings.length;
1622 for (int i = 0; i < len; i++) {
1623 zoneNames = zoneStrings[i];
1624 if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
1625 if (nameIndex <= 2) {
1626 useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
1628 tz = TimeZone.getTimeZone(zoneNames[0]);
1633 if (tz != null) { // Matched any ?
1634 if (!tz.equals(currentTimeZone)) {
1637 // If the time zone matched uses the same name
1638 // (abbreviation) for both standard and daylight time,
1639 // let the time zone in the Calendar decide which one.
1641 // Also if tz.getDSTSaving() returns 0 for DST, use tz to
1642 // determine the local time. (6645292)
1643 int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
1644 if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
1645 calb.set(Calendar.ZONE_OFFSET, tz.getRawOffset())
1646 .set(Calendar.DST_OFFSET, dstAmount);
1648 return (start + zoneNames[nameIndex].length());
1654 * Parses numeric forms of time zone offset, such as "hh:mm", and
1655 * sets calb to the parsed value.
1657 * @param text the text to be parsed
1658 * @param start the character position to start parsing
1659 * @param sign 1: positive; -1: negative
1660 * @param count 0: 'Z' or "GMT+hh:mm" parsing; 1 - 3: the number of 'X's
1661 * @param colon true - colon required between hh and mm; false - no colon required
1662 * @param calb a CalendarBuilder in which the parsed value is stored
1663 * @return updated parsed position, or its negative value to indicate a parsing error
1665 private int subParseNumericZone(String text, int start, int sign, int count,
1666 boolean colon, CalendarBuilder calb) {
1671 char c = text.charAt(index++);
1678 c = text.charAt(index++);
1680 hours = hours * 10 + (c - '0');
1682 // If no colon in RFC 822 or 'X' (ISO), two digits are
1684 if (count > 0 || !colon) {
1694 // Proceed with parsing mm
1695 c = text.charAt(index++);
1700 c = text.charAt(index++);
1706 c = text.charAt(index++);
1710 minutes = minutes * 10 + (c - '0');
1715 minutes += hours * 60;
1716 calb.set(Calendar.ZONE_OFFSET, minutes * MILLIS_PER_MINUTE * sign)
1717 .set(Calendar.DST_OFFSET, 0);
1719 } catch (IndexOutOfBoundsException e) {
1721 return 1 - index; // -(index - 1)
1724 private boolean isDigit(char c) {
1725 return c >= '0' && c <= '9';
1729 * Private member function that converts the parsed date strings into
1730 * timeFields. Returns -start (for ParsePosition) if failed.
1731 * @param text the time text to be parsed.
1732 * @param start where to start parsing.
1733 * @param ch the pattern character for the date field text to be parsed.
1734 * @param count the count of a pattern character.
1735 * @param obeyCount if true, then the next field directly abuts this one,
1736 * and we should use the count to know when to stop parsing.
1737 * @param ambiguousYear return parameter; upon return, if ambiguousYear[0]
1738 * is true, then a two-digit year was parsed and may need to be readjusted.
1739 * @param origPos origPos.errorIndex is used to return an error index
1740 * at which a parse error occurred, if matching failure occurs.
1741 * @return the new start position if matching succeeded; -1 indicating
1742 * matching failure, otherwise. In case matching failure occurred,
1743 * an error index is set to origPos.errorIndex.
1745 private int subParse(String text, int start, int patternCharIndex, int count,
1746 boolean obeyCount, boolean[] ambiguousYear,
1747 ParsePosition origPos,
1748 boolean useFollowingMinusSignAsDelimiter, CalendarBuilder calb) {
1749 Number number = null;
1751 ParsePosition pos = new ParsePosition(0);
1753 if (patternCharIndex == PATTERN_WEEK_YEAR && !calendar.isWeekDateSupported()) {
1754 // use calendar year 'y' instead
1755 patternCharIndex = PATTERN_YEAR;
1757 int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
1759 // If there are any spaces here, skip over them. If we hit the end
1760 // of the string, then fail.
1762 if (pos.index >= text.length()) {
1763 origPos.errorIndex = start;
1766 char c = text.charAt(pos.index);
1767 if (c != ' ' && c != '\t') break;
1773 // We handle a few special cases here where we need to parse
1774 // a number value. We handle further, more generic cases below. We need
1775 // to handle some of them here because some fields require extra processing on
1776 // the parsed value.
1777 if (patternCharIndex == PATTERN_HOUR_OF_DAY1 ||
1778 patternCharIndex == PATTERN_HOUR1 ||
1779 (patternCharIndex == PATTERN_MONTH && count <= 2) ||
1780 patternCharIndex == PATTERN_YEAR ||
1781 patternCharIndex == PATTERN_WEEK_YEAR) {
1782 // It would be good to unify this with the obeyCount logic below,
1783 // but that's going to be difficult.
1785 if ((start+count) > text.length()) {
1788 number = numberFormat.parse(text.substring(0, start+count), pos);
1790 number = numberFormat.parse(text, pos);
1792 if (number == null) {
1793 if (patternCharIndex != PATTERN_YEAR || calendar instanceof GregorianCalendar) {
1797 value = number.intValue();
1799 if (useFollowingMinusSignAsDelimiter && (value < 0) &&
1800 (((pos.index < text.length()) &&
1801 (text.charAt(pos.index) != minusSign)) ||
1802 ((pos.index == text.length()) &&
1803 (text.charAt(pos.index-1) == minusSign)))) {
1810 boolean useDateFormatSymbols = useDateFormatSymbols();
1813 switch (patternCharIndex) {
1814 case PATTERN_ERA: // 'G'
1815 if (useDateFormatSymbols) {
1816 if ((index = matchString(text, start, Calendar.ERA, formatData.getEras(), calb)) > 0) {
1820 Map<String, Integer> map = calendar.getDisplayNames(field,
1821 Calendar.ALL_STYLES,
1823 if ((index = matchString(text, start, field, map, calb)) > 0) {
1829 case PATTERN_WEEK_YEAR: // 'Y'
1830 case PATTERN_YEAR: // 'y'
1831 if (!(calendar instanceof GregorianCalendar)) {
1832 // calendar might have text representations for year values,
1833 // such as "\u5143" in JapaneseImperialCalendar.
1834 int style = (count >= 4) ? Calendar.LONG : Calendar.SHORT;
1835 Map<String, Integer> map = calendar.getDisplayNames(field, style, locale);
1837 if ((index = matchString(text, start, field, map, calb)) > 0) {
1841 calb.set(field, value);
1845 // If there are 3 or more YEAR pattern characters, this indicates
1846 // that the year value is to be treated literally, without any
1847 // two-digit year adjustments (e.g., from "01" to 2001). Otherwise
1848 // we made adjustments to place the 2-digit year in the proper
1849 // century, for parsed strings from "00" to "99". Any other string
1850 // is treated literally: "2250", "-1", "1", "002".
1851 if (count <= 2 && (pos.index - start) == 2
1852 && Character.isDigit(text.charAt(start))
1853 && Character.isDigit(text.charAt(start+1))) {
1854 // Assume for example that the defaultCenturyStart is 6/18/1903.
1855 // This means that two-digit years will be forced into the range
1856 // 6/18/1903 to 6/17/2003. As a result, years 00, 01, and 02
1857 // correspond to 2000, 2001, and 2002. Years 04, 05, etc. correspond
1858 // to 1904, 1905, etc. If the year is 03, then it is 2003 if the
1859 // other fields specify a date before 6/18, or 1903 if they specify a
1860 // date afterwards. As a result, 03 is an ambiguous year. All other
1861 // two-digit years are unambiguous.
1862 int ambiguousTwoDigitYear = defaultCenturyStartYear % 100;
1863 ambiguousYear[0] = value == ambiguousTwoDigitYear;
1864 value += (defaultCenturyStartYear/100)*100 +
1865 (value < ambiguousTwoDigitYear ? 100 : 0);
1867 calb.set(field, value);
1870 case PATTERN_MONTH: // 'M'
1871 if (count <= 2) // i.e., M or MM.
1873 // Don't want to parse the month if it is a string
1874 // while pattern uses numeric style: M or MM.
1875 // [We computed 'value' above.]
1876 calb.set(Calendar.MONTH, value - 1);
1880 if (useDateFormatSymbols) {
1881 // count >= 3 // i.e., MMM or MMMM
1882 // Want to be able to parse both short and long forms.
1883 // Try count == 4 first:
1885 if ((newStart = matchString(text, start, Calendar.MONTH,
1886 formatData.getMonths(), calb)) > 0) {
1889 // count == 4 failed, now try count == 3
1890 if ((index = matchString(text, start, Calendar.MONTH,
1891 formatData.getShortMonths(), calb)) > 0) {
1895 Map<String, Integer> map = calendar.getDisplayNames(field,
1896 Calendar.ALL_STYLES,
1898 if ((index = matchString(text, start, field, map, calb)) > 0) {
1904 case PATTERN_HOUR_OF_DAY1: // 'k' 1-based. eg, 23:59 + 1 hour =>> 24:59
1906 // Validate the hour value in non-lenient
1907 if (value < 1 || value > 24) {
1911 // [We computed 'value' above.]
1912 if (value == calendar.getMaximum(Calendar.HOUR_OF_DAY)+1)
1914 calb.set(Calendar.HOUR_OF_DAY, value);
1917 case PATTERN_DAY_OF_WEEK: // 'E'
1919 if (useDateFormatSymbols) {
1920 // Want to be able to parse both short and long forms.
1921 // Try count == 4 (DDDD) first:
1923 if ((newStart=matchString(text, start, Calendar.DAY_OF_WEEK,
1924 formatData.getWeekdays(), calb)) > 0) {
1927 // DDDD failed, now try DDD
1928 if ((index = matchString(text, start, Calendar.DAY_OF_WEEK,
1929 formatData.getShortWeekdays(), calb)) > 0) {
1933 int[] styles = { Calendar.LONG, Calendar.SHORT };
1934 for (int style : styles) {
1935 Map<String,Integer> map = calendar.getDisplayNames(field, style, locale);
1936 if ((index = matchString(text, start, field, map, calb)) > 0) {
1944 case PATTERN_AM_PM: // 'a'
1945 if (useDateFormatSymbols) {
1946 if ((index = matchString(text, start, Calendar.AM_PM,
1947 formatData.getAmPmStrings(), calb)) > 0) {
1951 Map<String,Integer> map = calendar.getDisplayNames(field, Calendar.ALL_STYLES, locale);
1952 if ((index = matchString(text, start, field, map, calb)) > 0) {
1958 case PATTERN_HOUR1: // 'h' 1-based. eg, 11PM + 1 hour =>> 12 AM
1960 // Validate the hour value in non-lenient
1961 if (value < 1 || value > 12) {
1965 // [We computed 'value' above.]
1966 if (value == calendar.getLeastMaximum(Calendar.HOUR)+1)
1968 calb.set(Calendar.HOUR, value);
1971 case PATTERN_ZONE_NAME: // 'z'
1972 case PATTERN_ZONE_VALUE: // 'Z'
1976 char c = text.charAt(pos.index);
1979 } else if (c == '-') {
1983 // Try parsing a custom time zone "GMT+hh:mm" or "GMT".
1984 if ((c == 'G' || c == 'g')
1985 && (text.length() - start) >= GMT.length()
1986 && text.regionMatches(true, start, GMT, 0, GMT.length())) {
1987 pos.index = start + GMT.length();
1989 if ((text.length() - pos.index) > 0) {
1990 c = text.charAt(pos.index);
1993 } else if (c == '-') {
1998 if (sign == 0) { /* "GMT" without offset */
1999 calb.set(Calendar.ZONE_OFFSET, 0)
2000 .set(Calendar.DST_OFFSET, 0);
2004 // Parse the rest as "hh:mm"
2005 int i = subParseNumericZone(text, ++pos.index,
2006 sign, 0, true, calb);
2012 // Try parsing the text as a time zone
2013 // name or abbreviation.
2014 int i = subParseZoneString(text, pos.index, calb);
2021 // Parse the rest as "hhmm" (RFC 822)
2022 int i = subParseNumericZone(text, ++pos.index,
2023 sign, 0, false, calb);
2029 } catch (IndexOutOfBoundsException e) {
2034 case PATTERN_ISO_ZONE: // 'X'
2036 if ((text.length() - pos.index) <= 0) {
2041 char c = text.charAt(pos.index);
2043 calb.set(Calendar.ZONE_OFFSET, 0).set(Calendar.DST_OFFSET, 0);
2047 // parse text as "+/-hh[[:]mm]" based on count
2050 } else if (c == '-') {
2056 int i = subParseNumericZone(text, ++pos.index, sign, count,
2066 // case PATTERN_DAY_OF_MONTH: // 'd'
2067 // case PATTERN_HOUR_OF_DAY0: // 'H' 0-based. eg, 23:59 + 1 hour =>> 00:59
2068 // case PATTERN_MINUTE: // 'm'
2069 // case PATTERN_SECOND: // 's'
2070 // case PATTERN_MILLISECOND: // 'S'
2071 // case PATTERN_DAY_OF_YEAR: // 'D'
2072 // case PATTERN_DAY_OF_WEEK_IN_MONTH: // 'F'
2073 // case PATTERN_WEEK_OF_YEAR: // 'w'
2074 // case PATTERN_WEEK_OF_MONTH: // 'W'
2075 // case PATTERN_HOUR0: // 'K' 0-based. eg, 11PM + 1 hour =>> 0 AM
2076 // case PATTERN_ISO_DAY_OF_WEEK: // 'u' (pseudo field);
2078 // Handle "generic" fields
2080 if ((start+count) > text.length()) {
2083 number = numberFormat.parse(text.substring(0, start+count), pos);
2085 number = numberFormat.parse(text, pos);
2087 if (number != null) {
2088 value = number.intValue();
2090 if (useFollowingMinusSignAsDelimiter && (value < 0) &&
2091 (((pos.index < text.length()) &&
2092 (text.charAt(pos.index) != minusSign)) ||
2093 ((pos.index == text.length()) &&
2094 (text.charAt(pos.index-1) == minusSign)))) {
2099 calb.set(field, value);
2107 origPos.errorIndex = pos.index;
2111 private final String getCalendarName() {
2112 return calendar.getClass().getName();
2115 private boolean useDateFormatSymbols() {
2116 if (useDateFormatSymbols) {
2119 return isGregorianCalendar() || locale == null;
2122 private boolean isGregorianCalendar() {
2123 return "java.util.GregorianCalendar".equals(getCalendarName());
2127 * Translates a pattern, mapping each character in the from string to the
2128 * corresponding character in the to string.
2130 * @exception IllegalArgumentException if the given pattern is invalid
2132 private String translatePattern(String pattern, String from, String to) {
2133 StringBuilder result = new StringBuilder();
2134 boolean inQuote = false;
2135 for (int i = 0; i < pattern.length(); ++i) {
2136 char c = pattern.charAt(i);
2144 else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
2145 int ci = from.indexOf(c);
2147 // patternChars is longer than localPatternChars due
2148 // to serialization compatibility. The pattern letters
2149 // unsupported by localPatternChars pass through.
2150 if (ci < to.length()) {
2154 throw new IllegalArgumentException("Illegal pattern " +
2163 throw new IllegalArgumentException("Unfinished quote in pattern");
2164 return result.toString();
2168 * Returns a pattern string describing this date format.
2170 * @return a pattern string describing this date format.
2172 public String toPattern() {
2177 * Returns a localized pattern string describing this date format.
2179 * @return a localized pattern string describing this date format.
2181 public String toLocalizedPattern() {
2182 return translatePattern(pattern,
2183 DateFormatSymbols.patternChars,
2184 formatData.getLocalPatternChars());
2188 * Applies the given pattern string to this date format.
2190 * @param pattern the new date and time pattern for this date format
2191 * @exception NullPointerException if the given pattern is null
2192 * @exception IllegalArgumentException if the given pattern is invalid
2194 public void applyPattern(String pattern)
2196 compiledPattern = compile(pattern);
2197 this.pattern = pattern;
2201 * Applies the given localized pattern string to this date format.
2203 * @param pattern a String to be mapped to the new date and time format
2204 * pattern for this format
2205 * @exception NullPointerException if the given pattern is null
2206 * @exception IllegalArgumentException if the given pattern is invalid
2208 public void applyLocalizedPattern(String pattern) {
2209 String p = translatePattern(pattern,
2210 formatData.getLocalPatternChars(),
2211 DateFormatSymbols.patternChars);
2212 compiledPattern = compile(p);
2217 * Gets a copy of the date and time format symbols of this date format.
2219 * @return the date and time format symbols of this date format
2220 * @see #setDateFormatSymbols
2222 public DateFormatSymbols getDateFormatSymbols()
2224 return (DateFormatSymbols)formatData.clone();
2228 * Sets the date and time format symbols of this date format.
2230 * @param newFormatSymbols the new date and time format symbols
2231 * @exception NullPointerException if the given newFormatSymbols is null
2232 * @see #getDateFormatSymbols
2234 public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols)
2236 this.formatData = (DateFormatSymbols)newFormatSymbols.clone();
2237 useDateFormatSymbols = true;
2241 * Creates a copy of this <code>SimpleDateFormat</code>. This also
2242 * clones the format's date format symbols.
2244 * @return a clone of this <code>SimpleDateFormat</code>
2246 public Object clone() {
2247 SimpleDateFormat other = (SimpleDateFormat) super.clone();
2248 other.formatData = (DateFormatSymbols) formatData.clone();
2253 * Returns the hash code value for this <code>SimpleDateFormat</code> object.
2255 * @return the hash code value for this <code>SimpleDateFormat</code> object.
2257 public int hashCode()
2259 return pattern.hashCode();
2260 // just enough fields for a reasonable distribution
2264 * Compares the given object with this <code>SimpleDateFormat</code> for
2267 * @return true if the given object is equal to this
2268 * <code>SimpleDateFormat</code>
2270 public boolean equals(Object obj)
2272 if (!super.equals(obj)) return false; // super does class check
2273 SimpleDateFormat that = (SimpleDateFormat) obj;
2274 return (pattern.equals(that.pattern)
2275 && formatData.equals(that.formatData));
2279 * After reading an object from the input stream, the format
2280 * pattern in the object is verified.
2282 * @exception InvalidObjectException if the pattern is invalid
2284 private void readObject(ObjectInputStream stream)
2285 throws IOException, ClassNotFoundException {
2286 stream.defaultReadObject();
2289 compiledPattern = compile(pattern);
2290 } catch (Exception e) {
2291 throw new InvalidObjectException("invalid pattern");
2294 if (serialVersionOnStream < 1) {
2295 // didn't have defaultCenturyStart field
2296 initializeDefaultCentury();
2299 // fill in dependent transient field
2300 parseAmbiguousDatesAsAfter(defaultCenturyStart);
2302 serialVersionOnStream = currentSerialVersion;
2304 // If the deserialized object has a SimpleTimeZone, try
2305 // to replace it with a ZoneInfo equivalent in order to
2306 // be compatible with the SimpleTimeZone-based
2307 // implementation as much as possible.
2308 TimeZone tz = getTimeZone();
2309 if (tz instanceof SimpleTimeZone) {
2310 String id = tz.getID();
2311 TimeZone zi = TimeZone.getTimeZone(id);
2312 if (zi != null && zi.hasSameRules(tz) && zi.getID().equals(id)) {
2319 * Analyze the negative subpattern of DecimalFormat and set/update values
2322 private void checkNegativeNumberExpression() {
2323 if ((numberFormat instanceof DecimalFormat) &&
2324 !numberFormat.equals(originalNumberFormat)) {
2325 String numberPattern = ((DecimalFormat)numberFormat).toPattern();
2326 if (!numberPattern.equals(originalNumberPattern)) {
2327 hasFollowingMinusSign = false;
2329 int separatorIndex = numberPattern.indexOf(';');
2330 // If the negative subpattern is not absent, we have to analayze
2331 // it in order to check if it has a following minus sign.
2332 if (separatorIndex > -1) {
2333 int minusIndex = numberPattern.indexOf('-', separatorIndex);
2334 if ((minusIndex > numberPattern.lastIndexOf('0')) &&
2335 (minusIndex > numberPattern.lastIndexOf('#'))) {
2336 hasFollowingMinusSign = true;
2337 minusSign = ((DecimalFormat)numberFormat).getDecimalFormatSymbols().getMinusSign();
2340 originalNumberPattern = numberPattern;
2342 originalNumberFormat = numberFormat;
2346 private static final class GregorianCalendar extends Calendar {
2348 protected void computeTime() {
2352 protected void computeFields() {
2356 public void add(int field, int amount) {
2360 public void roll(int field, boolean up) {
2364 public int getMinimum(int field) {
2369 public int getMaximum(int field) {
2374 public int getGreatestMinimum(int field) {
2379 public int getLeastMaximum(int field) {