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.GregorianCalendar;
47 import java.util.Locale;
49 import java.util.MissingResourceException;
50 import java.util.ResourceBundle;
51 import java.util.SimpleTimeZone;
52 import java.util.TimeZone;
53 import java.util.concurrent.ConcurrentHashMap;
54 import java.util.concurrent.ConcurrentMap;
55 import sun.util.calendar.CalendarUtils;
56 import sun.util.calendar.ZoneInfoFile;
57 import sun.util.resources.LocaleData;
59 import static java.text.DateFormatSymbols.*;
62 * <code>SimpleDateFormat</code> is a concrete class for formatting and
63 * parsing dates in a locale-sensitive manner. It allows for formatting
64 * (date -> text), parsing (text -> date), and normalization.
67 * <code>SimpleDateFormat</code> allows you to start by choosing
68 * any user-defined patterns for date-time formatting. However, you
69 * are encouraged to create a date-time formatter with either
70 * <code>getTimeInstance</code>, <code>getDateInstance</code>, or
71 * <code>getDateTimeInstance</code> in <code>DateFormat</code>. Each
72 * of these class methods can return a date/time formatter initialized
73 * with a default format pattern. You may modify the format pattern
74 * using the <code>applyPattern</code> methods as desired.
75 * For more information on using these methods, see
78 * <h4>Date and Time Patterns</h4>
80 * Date and time formats are specified by <em>date and time pattern</em>
82 * Within date and time pattern strings, unquoted letters from
83 * <code>'A'</code> to <code>'Z'</code> and from <code>'a'</code> to
84 * <code>'z'</code> are interpreted as pattern letters representing the
85 * components of a date or time string.
86 * Text can be quoted using single quotes (<code>'</code>) to avoid
88 * <code>"''"</code> represents a single quote.
89 * All other characters are not interpreted; they're simply copied into the
90 * output string during formatting or matched against the input string
93 * The following pattern letters are defined (all other characters from
94 * <code>'A'</code> to <code>'Z'</code> and from <code>'a'</code> to
95 * <code>'z'</code> are reserved):
97 * <table border=0 cellspacing=3 cellpadding=0 summary="Chart shows pattern letters, date/time component, presentation, and examples.">
98 * <tr bgcolor="#ccccff">
99 * <th align=left>Letter
100 * <th align=left>Date or Time Component
101 * <th align=left>Presentation
102 * <th align=left>Examples
106 * <td><a href="#text">Text</a>
107 * <td><code>AD</code>
108 * <tr bgcolor="#eeeeff">
111 * <td><a href="#year">Year</a>
112 * <td><code>1996</code>; <code>96</code>
116 * <td><a href="#year">Year</a>
117 * <td><code>2009</code>; <code>09</code>
118 * <tr bgcolor="#eeeeff">
121 * <td><a href="#month">Month</a>
122 * <td><code>July</code>; <code>Jul</code>; <code>07</code>
126 * <td><a href="#number">Number</a>
127 * <td><code>27</code>
128 * <tr bgcolor="#eeeeff">
131 * <td><a href="#number">Number</a>
136 * <td><a href="#number">Number</a>
137 * <td><code>189</code>
138 * <tr bgcolor="#eeeeff">
141 * <td><a href="#number">Number</a>
142 * <td><code>10</code>
145 * <td>Day of week in month
146 * <td><a href="#number">Number</a>
148 * <tr bgcolor="#eeeeff">
150 * <td>Day name in week
151 * <td><a href="#text">Text</a>
152 * <td><code>Tuesday</code>; <code>Tue</code>
155 * <td>Day number of week (1 = Monday, ..., 7 = Sunday)
156 * <td><a href="#number">Number</a>
158 * <tr bgcolor="#eeeeff">
161 * <td><a href="#text">Text</a>
162 * <td><code>PM</code>
165 * <td>Hour in day (0-23)
166 * <td><a href="#number">Number</a>
168 * <tr bgcolor="#eeeeff">
170 * <td>Hour in day (1-24)
171 * <td><a href="#number">Number</a>
172 * <td><code>24</code>
175 * <td>Hour in am/pm (0-11)
176 * <td><a href="#number">Number</a>
178 * <tr bgcolor="#eeeeff">
180 * <td>Hour in am/pm (1-12)
181 * <td><a href="#number">Number</a>
182 * <td><code>12</code>
186 * <td><a href="#number">Number</a>
187 * <td><code>30</code>
188 * <tr bgcolor="#eeeeff">
190 * <td>Second in minute
191 * <td><a href="#number">Number</a>
192 * <td><code>55</code>
196 * <td><a href="#number">Number</a>
197 * <td><code>978</code>
198 * <tr bgcolor="#eeeeff">
201 * <td><a href="#timezone">General time zone</a>
202 * <td><code>Pacific Standard Time</code>; <code>PST</code>; <code>GMT-08:00</code>
206 * <td><a href="#rfc822timezone">RFC 822 time zone</a>
207 * <td><code>-0800</code>
208 * <tr bgcolor="#eeeeff">
211 * <td><a href="#iso8601timezone">ISO 8601 time zone</a>
212 * <td><code>-08</code>; <code>-0800</code>; <code>-08:00</code>
215 * Pattern letters are usually repeated, as their number determines the
216 * exact presentation:
218 * <li><strong><a name="text">Text:</a></strong>
219 * For formatting, if the number of pattern letters is 4 or more,
220 * the full form is used; otherwise a short or abbreviated form
221 * is used if available.
222 * For parsing, both forms are accepted, independent of the number
223 * of pattern letters.<br><br></li>
224 * <li><strong><a name="number">Number:</a></strong>
225 * For formatting, the number of pattern letters is the minimum
226 * number of digits, and shorter numbers are zero-padded to this amount.
227 * For parsing, the number of pattern letters is ignored unless
228 * it's needed to separate two adjacent fields.<br><br></li>
229 * <li><strong><a name="year">Year:</a></strong>
230 * If the formatter's {@link #getCalendar() Calendar} is the Gregorian
231 * calendar, the following rules are applied.<br>
233 * <li>For formatting, if the number of pattern letters is 2, the year
234 * is truncated to 2 digits; otherwise it is interpreted as a
235 * <a href="#number">number</a>.
236 * <li>For parsing, if the number of pattern letters is more than 2,
237 * the year is interpreted literally, regardless of the number of
238 * digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to
240 * <li>For parsing with the abbreviated year pattern ("y" or "yy"),
241 * <code>SimpleDateFormat</code> must interpret the abbreviated year
242 * relative to some century. It does this by adjusting dates to be
243 * within 80 years before and 20 years after the time the <code>SimpleDateFormat</code>
244 * instance is created. For example, using a pattern of "MM/dd/yy" and a
245 * <code>SimpleDateFormat</code> instance created on Jan 1, 1997, the string
246 * "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64"
247 * would be interpreted as May 4, 1964.
248 * During parsing, only strings consisting of exactly two digits, as defined by
249 * {@link Character#isDigit(char)}, will be parsed into the default century.
250 * Any other numeric string, such as a one digit string, a three or more digit
251 * string, or a two digit string that isn't all digits (for example, "-1"), is
252 * interpreted literally. So "01/02/3" or "01/02/003" are parsed, using the
253 * same pattern, as Jan 2, 3 AD. Likewise, "01/02/-3" is parsed as Jan 2, 4 BC.
255 * Otherwise, calendar system specific forms are applied.
256 * For both formatting and parsing, if the number of pattern
257 * letters is 4 or more, a calendar specific {@linkplain
258 * Calendar#LONG long form} is used. Otherwise, a calendar
259 * specific {@linkplain Calendar#SHORT short or abbreviated form}
262 * If week year {@code 'Y'} is specified and the {@linkplain
263 * #getCalendar() calendar} doesn't support any <a
264 * href="../util/GregorianCalendar.html#week_year"> week
265 * years</a>, the calendar year ({@code 'y'}) is used instead. The
266 * support of week years can be tested with a call to {@link
267 * DateFormat#getCalendar() getCalendar()}.{@link
268 * java.util.Calendar#isWeekDateSupported()
269 * isWeekDateSupported()}.<br><br></li>
270 * <li><strong><a name="month">Month:</a></strong>
271 * If the number of pattern letters is 3 or more, the month is
272 * interpreted as <a href="#text">text</a>; otherwise,
273 * it is interpreted as a <a href="#number">number</a>.<br><br></li>
274 * <li><strong><a name="timezone">General time zone:</a></strong>
275 * Time zones are interpreted as <a href="#text">text</a> if they have
276 * names. For time zones representing a GMT offset value, the
277 * following syntax is used:
279 * <a name="GMTOffsetTimeZone"><i>GMTOffsetTimeZone:</i></a>
280 * <code>GMT</code> <i>Sign</i> <i>Hours</i> <code>:</code> <i>Minutes</i>
281 * <i>Sign:</i> one of
285 * <i>Digit</i> <i>Digit</i>
287 * <i>Digit</i> <i>Digit</i>
288 * <i>Digit:</i> one of
289 * <code>0 1 2 3 4 5 6 7 8 9</code></pre>
290 * <i>Hours</i> must be between 0 and 23, and <i>Minutes</i> must be between
291 * 00 and 59. The format is locale independent and digits must be taken
292 * from the Basic Latin block of the Unicode standard.
293 * <p>For parsing, <a href="#rfc822timezone">RFC 822 time zones</a> are also
294 * accepted.<br><br></li>
295 * <li><strong><a name="rfc822timezone">RFC 822 time zone:</a></strong>
296 * For formatting, the RFC 822 4-digit time zone format is used:
299 * <i>RFC822TimeZone:</i>
300 * <i>Sign</i> <i>TwoDigitHours</i> <i>Minutes</i>
301 * <i>TwoDigitHours:</i>
302 * <i>Digit Digit</i></pre>
303 * <i>TwoDigitHours</i> must be between 00 and 23. Other definitions
304 * are as for <a href="#timezone">general time zones</a>.
306 * <p>For parsing, <a href="#timezone">general time zones</a> are also
308 * <li><strong><a name="iso8601timezone">ISO 8601 Time zone:</a></strong>
309 * The number of pattern letters designates the format for both formatting
310 * and parsing as follows:
312 * <i>ISO8601TimeZone:</i>
313 * <i>OneLetterISO8601TimeZone</i>
314 * <i>TwoLetterISO8601TimeZone</i>
315 * <i>ThreeLetterISO8601TimeZone</i>
316 * <i>OneLetterISO8601TimeZone:</i>
317 * <i>Sign</i> <i>TwoDigitHours</i>
319 * <i>TwoLetterISO8601TimeZone:</i>
320 * <i>Sign</i> <i>TwoDigitHours</i> <i>Minutes</i>
322 * <i>ThreeLetterISO8601TimeZone:</i>
323 * <i>Sign</i> <i>TwoDigitHours</i> {@code :} <i>Minutes</i>
325 * Other definitions are as for <a href="#timezone">general time zones</a> or
326 * <a href="#rfc822timezone">RFC 822 time zones</a>.
328 * <p>For formatting, if the offset value from GMT is 0, {@code "Z"} is
329 * produced. If the number of pattern letters is 1, any fraction of an hour
330 * is ignored. For example, if the pattern is {@code "X"} and the time zone is
331 * {@code "GMT+05:30"}, {@code "+05"} is produced.
333 * <p>For parsing, {@code "Z"} is parsed as the UTC time zone designator.
334 * <a href="#timezone">General time zones</a> are <em>not</em> accepted.
336 * <p>If the number of pattern letters is 4 or more, {@link
337 * IllegalArgumentException} is thrown when constructing a {@code
338 * SimpleDateFormat} or {@linkplain #applyPattern(String) applying a
341 * <code>SimpleDateFormat</code> also supports <em>localized date and time
342 * pattern</em> strings. In these strings, the pattern letters described above
343 * may be replaced with other, locale dependent, pattern letters.
344 * <code>SimpleDateFormat</code> does not deal with the localization of text
345 * other than the pattern letters; that's up to the client of the class.
350 * The following examples show how date and time patterns are interpreted in
351 * the U.S. locale. The given date and time are 2001-07-04 12:08:56 local time
352 * in the U.S. Pacific Time time zone.
354 * <table border=0 cellspacing=3 cellpadding=0 summary="Examples of date and time patterns interpreted in the U.S. locale">
355 * <tr bgcolor="#ccccff">
356 * <th align=left>Date and Time Pattern
357 * <th align=left>Result
359 * <td><code>"yyyy.MM.dd G 'at' HH:mm:ss z"</code>
360 * <td><code>2001.07.04 AD at 12:08:56 PDT</code>
361 * <tr bgcolor="#eeeeff">
362 * <td><code>"EEE, MMM d, ''yy"</code>
363 * <td><code>Wed, Jul 4, '01</code>
365 * <td><code>"h:mm a"</code>
366 * <td><code>12:08 PM</code>
367 * <tr bgcolor="#eeeeff">
368 * <td><code>"hh 'o''clock' a, zzzz"</code>
369 * <td><code>12 o'clock PM, Pacific Daylight Time</code>
371 * <td><code>"K:mm a, z"</code>
372 * <td><code>0:08 PM, PDT</code>
373 * <tr bgcolor="#eeeeff">
374 * <td><code>"yyyyy.MMMMM.dd GGG hh:mm aaa"</code>
375 * <td><code>02001.July.04 AD 12:08 PM</code>
377 * <td><code>"EEE, d MMM yyyy HH:mm:ss Z"</code>
378 * <td><code>Wed, 4 Jul 2001 12:08:56 -0700</code>
379 * <tr bgcolor="#eeeeff">
380 * <td><code>"yyMMddHHmmssZ"</code>
381 * <td><code>010704120856-0700</code>
383 * <td><code>"yyyy-MM-dd'T'HH:mm:ss.SSSZ"</code>
384 * <td><code>2001-07-04T12:08:56.235-0700</code>
385 * <tr bgcolor="#eeeeff">
386 * <td><code>"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"</code>
387 * <td><code>2001-07-04T12:08:56.235-07:00</code>
389 * <td><code>"YYYY-'W'ww-u"</code>
390 * <td><code>2001-W27-3</code>
394 * <h4><a name="synchronization">Synchronization</a></h4>
397 * Date formats are not synchronized.
398 * It is recommended to create separate format instances for each thread.
399 * If multiple threads access a format concurrently, it must be synchronized
402 * @see <a href="http://java.sun.com/docs/books/tutorial/i18n/format/simpleDateFormat.html">Java Tutorial</a>
403 * @see java.util.Calendar
404 * @see java.util.TimeZone
406 * @see DateFormatSymbols
407 * @author Mark Davis, Chen-Lieh Huang, Alan Liu
409 public class SimpleDateFormat extends DateFormat {
411 // the official serial version ID which says cryptically
412 // which version we're compatible with
413 static final long serialVersionUID = 4774881970558875024L;
415 // the internal serial version which says which version was written
416 // - 0 (default) for version up to JDK 1.1.3
417 // - 1 for version from JDK 1.1.4, which includes a new field
418 static final int currentSerialVersion = 1;
421 * The version of the serialized data on the stream. Possible values:
423 * <li><b>0</b> or not present on stream: JDK 1.1.3. This version
424 * has no <code>defaultCenturyStart</code> on stream.
425 * <li><b>1</b> JDK 1.1.4 or later. This version adds
426 * <code>defaultCenturyStart</code>.
428 * When streaming out this class, the most recent format
429 * and the highest allowable <code>serialVersionOnStream</code>
434 private int serialVersionOnStream = currentSerialVersion;
437 * The pattern string of this formatter. This is always a non-localized
438 * pattern. May not be null. See class documentation for details.
441 private String pattern;
444 * Saved numberFormat and pattern.
445 * @see SimpleDateFormat#checkNegativeNumberExpression
447 transient private NumberFormat originalNumberFormat;
448 transient private String originalNumberPattern;
451 * The minus sign to be used with format and parse.
453 transient private char minusSign = '-';
456 * True when a negative sign follows a number.
457 * (True as default in Arabic.)
459 transient private boolean hasFollowingMinusSign = false;
462 * The compiled pattern.
464 transient private char[] compiledPattern;
467 * Tags for the compiled pattern.
469 private final static int TAG_QUOTE_ASCII_CHAR = 100;
470 private final static int TAG_QUOTE_CHARS = 101;
473 * Locale dependent digit zero.
474 * @see #zeroPaddingNumber
475 * @see java.text.DecimalFormatSymbols#getZeroDigit
477 transient private char zeroDigit;
480 * The symbols used by this formatter for week names, month names,
481 * etc. May not be null.
483 * @see java.text.DateFormatSymbols
485 private DateFormatSymbols formatData;
488 * We map dates with two-digit years into the century starting at
489 * <code>defaultCenturyStart</code>, which may be any date. May
494 private Date defaultCenturyStart;
496 transient private int defaultCenturyStartYear;
498 private static final int MILLIS_PER_MINUTE = 60 * 1000;
500 // For time zones that have no names, use strings GMT+minutes and
501 // GMT-minutes. For instance, in France the time zone is GMT+60.
502 private static final String GMT = "GMT";
505 * Cache to hold the DateTimePatterns of a Locale.
507 private static final ConcurrentMap<Locale, String[]> cachedLocaleData
508 = new ConcurrentHashMap<Locale, String[]>(3);
511 * Cache NumberFormat instances with Locale key.
513 private static final ConcurrentMap<Locale, NumberFormat> cachedNumberFormatData
514 = new ConcurrentHashMap<Locale, NumberFormat>(3);
517 * The Locale used to instantiate this
518 * <code>SimpleDateFormat</code>. The value may be null if this object
519 * has been created by an older <code>SimpleDateFormat</code> and
525 private Locale locale;
528 * Indicates whether this <code>SimpleDateFormat</code> should use
529 * the DateFormatSymbols. If true, the format and parse methods
530 * use the DateFormatSymbols values. If false, the format and
531 * parse methods call Calendar.getDisplayName or
532 * Calendar.getDisplayNames.
534 transient boolean useDateFormatSymbols;
537 * Constructs a <code>SimpleDateFormat</code> using the default pattern and
538 * date format symbols for the default locale.
539 * <b>Note:</b> This constructor may not support all locales.
540 * For full coverage, use the factory methods in the {@link DateFormat}
543 public SimpleDateFormat() {
544 this(SHORT, SHORT, Locale.getDefault(Locale.Category.FORMAT));
548 * Constructs a <code>SimpleDateFormat</code> using the given pattern and
549 * the default date format symbols for the default locale.
550 * <b>Note:</b> This constructor may not support all locales.
551 * For full coverage, use the factory methods in the {@link DateFormat}
554 * @param pattern the pattern describing the date and time format
555 * @exception NullPointerException if the given pattern is null
556 * @exception IllegalArgumentException if the given pattern is invalid
558 public SimpleDateFormat(String pattern)
560 this(pattern, Locale.getDefault(Locale.Category.FORMAT));
564 * Constructs a <code>SimpleDateFormat</code> using the given pattern and
565 * the default date format symbols for the given locale.
566 * <b>Note:</b> This constructor may not support all locales.
567 * For full coverage, use the factory methods in the {@link DateFormat}
570 * @param pattern the pattern describing the date and time format
571 * @param locale the locale whose date format symbols should be used
572 * @exception NullPointerException if the given pattern or locale is null
573 * @exception IllegalArgumentException if the given pattern is invalid
575 public SimpleDateFormat(String pattern, Locale locale)
577 if (pattern == null || locale == null) {
578 throw new NullPointerException();
581 initializeCalendar(locale);
582 this.pattern = pattern;
583 this.formatData = DateFormatSymbols.getInstanceRef(locale);
584 this.locale = locale;
589 * Constructs a <code>SimpleDateFormat</code> using the given pattern and
590 * date format symbols.
592 * @param pattern the pattern describing the date and time format
593 * @param formatSymbols the date format symbols to be used for formatting
594 * @exception NullPointerException if the given pattern or formatSymbols is null
595 * @exception IllegalArgumentException if the given pattern is invalid
597 public SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)
599 if (pattern == null || formatSymbols == null) {
600 throw new NullPointerException();
603 this.pattern = pattern;
604 this.formatData = (DateFormatSymbols) formatSymbols.clone();
605 this.locale = Locale.getDefault(Locale.Category.FORMAT);
606 initializeCalendar(this.locale);
607 initialize(this.locale);
608 useDateFormatSymbols = true;
611 /* Package-private, called by DateFormat factory methods */
612 SimpleDateFormat(int timeStyle, int dateStyle, Locale loc) {
614 throw new NullPointerException();
618 // initialize calendar and related fields
619 initializeCalendar(loc);
621 /* try the cache first */
622 String[] dateTimePatterns = cachedLocaleData.get(loc);
623 if (dateTimePatterns == null) { /* cache miss */
624 ResourceBundle r = LocaleData.getDateFormatData(loc);
625 if (!isGregorianCalendar()) {
627 dateTimePatterns = r.getStringArray(getCalendarName() + ".DateTimePatterns");
628 } catch (MissingResourceException e) {
631 if (dateTimePatterns == null) {
632 dateTimePatterns = r.getStringArray("DateTimePatterns");
635 cachedLocaleData.putIfAbsent(loc, dateTimePatterns);
637 formatData = DateFormatSymbols.getInstanceRef(loc);
638 if ((timeStyle >= 0) && (dateStyle >= 0)) {
639 Object[] dateTimeArgs = {dateTimePatterns[timeStyle],
640 dateTimePatterns[dateStyle + 4]};
641 pattern = MessageFormat.format(dateTimePatterns[8], dateTimeArgs);
643 else if (timeStyle >= 0) {
644 pattern = dateTimePatterns[timeStyle];
646 else if (dateStyle >= 0) {
647 pattern = dateTimePatterns[dateStyle + 4];
650 throw new IllegalArgumentException("No date or time style specified");
656 /* Initialize compiledPattern and numberFormat fields */
657 private void initialize(Locale loc) {
658 // Verify and compile the given pattern.
659 compiledPattern = compile(pattern);
661 /* try the cache first */
662 numberFormat = cachedNumberFormatData.get(loc);
663 if (numberFormat == null) { /* cache miss */
664 numberFormat = NumberFormat.getIntegerInstance(loc);
665 numberFormat.setGroupingUsed(false);
668 cachedNumberFormatData.putIfAbsent(loc, numberFormat);
670 numberFormat = (NumberFormat) numberFormat.clone();
672 initializeDefaultCentury();
675 private void initializeCalendar(Locale loc) {
676 if (calendar == null) {
678 // The format object must be constructed using the symbols for this zone.
679 // However, the calendar should use the current default TimeZone.
680 // If this is not contained in the locale zone strings, then the zone
681 // will be formatted using generic GMT+/-H:MM nomenclature.
682 calendar = Calendar.getInstance(TimeZone.getDefault(), loc);
687 * Returns the compiled form of the given pattern. The syntax of
688 * the compiled pattern is:
708 * TAG_QUOTE_ASCII_CHAR ascii_char
712 * where `short_length' is an 8-bit unsigned integer between 0 and
713 * 254. `long_length' is a sequence of an 8-bit integer 255 and a
714 * 32-bit signed integer value which is split into upper and lower
715 * 16-bit fields in two char's. `pattern_char_index' is an 8-bit
716 * integer between 0 and 18. `ascii_char' is an 7-bit ASCII
717 * character value. `data' depends on its Tag value.
719 * If Length is short_length, Tag and short_length are packed in a
720 * single char, as illustrated below.
722 * char[0] = (Tag << 8) | short_length;
725 * If Length is long_length, Tag and 255 are packed in the first
726 * char and a 32-bit integer, as illustrated below.
728 * char[0] = (Tag << 8) | 255;
729 * char[1] = (char) (long_length >>> 16);
730 * char[2] = (char) (long_length & 0xffff);
733 * If Tag is a pattern_char_index, its Length is the number of
734 * pattern characters. For example, if the given pattern is
735 * "yyyy", Tag is 1 and Length is 4, followed by no data.
737 * If Tag is TAG_QUOTE_CHARS, its Length is the number of char's
738 * following the TagField. For example, if the given pattern is
739 * "'o''clock'", Length is 7 followed by a char sequence of
740 * <code>o&nbs;'&nbs;c&nbs;l&nbs;o&nbs;c&nbs;k</code>.
742 * TAG_QUOTE_ASCII_CHAR is a special tag and has an ASCII
743 * character in place of Length. For example, if the given pattern
744 * is "'o'", the TaggedData entry is
745 * <code>((TAG_QUOTE_ASCII_CHAR&nbs;<<&nbs;8)&nbs;|&nbs;'o')</code>.
747 * @exception NullPointerException if the given pattern is null
748 * @exception IllegalArgumentException if the given pattern is invalid
750 private char[] compile(String pattern) {
751 int length = pattern.length();
752 boolean inQuote = false;
753 StringBuilder compiledPattern = new StringBuilder(length * 2);
754 StringBuilder tmpBuffer = null;
758 for (int i = 0; i < length; i++) {
759 char c = pattern.charAt(i);
762 // '' is treated as a single quote regardless of being
763 // in a quoted section.
764 if ((i + 1) < length) {
765 c = pattern.charAt(i + 1);
769 encode(lastTag, count, compiledPattern);
776 compiledPattern.append((char)(TAG_QUOTE_ASCII_CHAR << 8 | c));
783 encode(lastTag, count, compiledPattern);
787 if (tmpBuffer == null) {
788 tmpBuffer = new StringBuilder(length);
790 tmpBuffer.setLength(0);
794 int len = tmpBuffer.length();
796 char ch = tmpBuffer.charAt(0);
798 compiledPattern.append((char)(TAG_QUOTE_ASCII_CHAR << 8 | ch));
800 compiledPattern.append((char)(TAG_QUOTE_CHARS << 8 | 1));
801 compiledPattern.append(ch);
804 encode(TAG_QUOTE_CHARS, len, compiledPattern);
805 compiledPattern.append(tmpBuffer);
815 if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
817 encode(lastTag, count, compiledPattern);
822 // In most cases, c would be a delimiter, such as ':'.
823 compiledPattern.append((char)(TAG_QUOTE_ASCII_CHAR << 8 | c));
825 // Take any contiguous non-ASCII alphabet characters and
826 // put them in a single TAG_QUOTE_CHARS.
828 for (j = i + 1; j < length; j++) {
829 char d = pattern.charAt(j);
830 if (d == '\'' || (d >= 'a' && d <= 'z' || d >= 'A' && d <= 'Z')) {
834 compiledPattern.append((char)(TAG_QUOTE_CHARS << 8 | (j - i)));
836 compiledPattern.append(pattern.charAt(i));
844 if ((tag = DateFormatSymbols.patternChars.indexOf(c)) == -1) {
845 throw new IllegalArgumentException("Illegal pattern character " +
848 if (lastTag == -1 || lastTag == tag) {
853 encode(lastTag, count, compiledPattern);
859 throw new IllegalArgumentException("Unterminated quote");
863 encode(lastTag, count, compiledPattern);
866 // Copy the compiled pattern to a char array
867 int len = compiledPattern.length();
868 char[] r = new char[len];
869 compiledPattern.getChars(0, len, r, 0);
874 * Encodes the given tag and length and puts encoded char(s) into buffer.
876 private static final void encode(int tag, int length, StringBuilder buffer) {
877 if (tag == PATTERN_ISO_ZONE && length >= 4) {
878 throw new IllegalArgumentException("invalid ISO 8601 format: length=" + length);
881 buffer.append((char)(tag << 8 | length));
883 buffer.append((char)((tag << 8) | 0xff));
884 buffer.append((char)(length >>> 16));
885 buffer.append((char)(length & 0xffff));
889 /* Initialize the fields we use to disambiguate ambiguous years. Separate
890 * so we can call it from readObject().
892 private void initializeDefaultCentury() {
893 calendar.setTimeInMillis(System.currentTimeMillis());
894 calendar.add( Calendar.YEAR, -80 );
895 parseAmbiguousDatesAsAfter(calendar.getTime());
898 /* Define one-century window into which to disambiguate dates using
901 private void parseAmbiguousDatesAsAfter(Date startDate) {
902 defaultCenturyStart = startDate;
903 calendar.setTime(startDate);
904 defaultCenturyStartYear = calendar.get(Calendar.YEAR);
908 * Sets the 100-year period 2-digit years will be interpreted as being in
909 * to begin on the date the user specifies.
911 * @param startDate During parsing, two digit years will be placed in the range
912 * <code>startDate</code> to <code>startDate + 100 years</code>.
913 * @see #get2DigitYearStart
916 public void set2DigitYearStart(Date startDate) {
917 parseAmbiguousDatesAsAfter(new Date(startDate.getTime()));
921 * Returns the beginning date of the 100-year period 2-digit years are interpreted
924 * @return the start of the 100-year period into which two digit years are
926 * @see #set2DigitYearStart
929 public Date get2DigitYearStart() {
930 return (Date) defaultCenturyStart.clone();
934 * Formats the given <code>Date</code> into a date/time string and appends
935 * the result to the given <code>StringBuffer</code>.
937 * @param date the date-time value to be formatted into a date-time string.
938 * @param toAppendTo where the new date-time text is to be appended.
939 * @param pos the formatting position. On input: an alignment field,
940 * if desired. On output: the offsets of the alignment field.
941 * @return the formatted date-time string.
942 * @exception NullPointerException if the given {@code date} is {@code null}.
944 public StringBuffer format(Date date, StringBuffer toAppendTo,
947 pos.beginIndex = pos.endIndex = 0;
948 return format(date, toAppendTo, pos.getFieldDelegate());
951 // Called from Format after creating a FieldDelegate
952 private StringBuffer format(Date date, StringBuffer toAppendTo,
953 FieldDelegate delegate) {
954 // Convert input date to time field list
955 calendar.setTime(date);
957 boolean useDateFormatSymbols = useDateFormatSymbols();
959 for (int i = 0; i < compiledPattern.length; ) {
960 int tag = compiledPattern[i] >>> 8;
961 int count = compiledPattern[i++] & 0xff;
963 count = compiledPattern[i++] << 16;
964 count |= compiledPattern[i++];
968 case TAG_QUOTE_ASCII_CHAR:
969 toAppendTo.append((char)count);
972 case TAG_QUOTE_CHARS:
973 toAppendTo.append(compiledPattern, i, count);
978 subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
986 * Formats an Object producing an <code>AttributedCharacterIterator</code>.
987 * You can use the returned <code>AttributedCharacterIterator</code>
988 * to build the resulting String, as well as to determine information
989 * about the resulting String.
991 * Each attribute key of the AttributedCharacterIterator will be of type
992 * <code>DateFormat.Field</code>, with the corresponding attribute value
993 * being the same as the attribute key.
995 * @exception NullPointerException if obj is null.
996 * @exception IllegalArgumentException if the Format cannot format the
997 * given object, or if the Format's pattern string is invalid.
998 * @param obj The object to format
999 * @return AttributedCharacterIterator describing the formatted value.
1002 public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
1003 StringBuffer sb = new StringBuffer();
1004 CharacterIteratorFieldDelegate delegate = new
1005 CharacterIteratorFieldDelegate();
1007 if (obj instanceof Date) {
1008 format((Date)obj, sb, delegate);
1010 else if (obj instanceof Number) {
1011 format(new Date(((Number)obj).longValue()), sb, delegate);
1013 else if (obj == null) {
1014 throw new NullPointerException(
1015 "formatToCharacterIterator must be passed non-null object");
1018 throw new IllegalArgumentException(
1019 "Cannot format given Object as a Date");
1021 return delegate.getIterator(sb.toString());
1024 // Map index into pattern character string to Calendar field number
1025 private static final int[] PATTERN_INDEX_TO_CALENDAR_FIELD =
1027 Calendar.ERA, Calendar.YEAR, Calendar.MONTH, Calendar.DATE,
1028 Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY, Calendar.MINUTE,
1029 Calendar.SECOND, Calendar.MILLISECOND, Calendar.DAY_OF_WEEK,
1030 Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK_IN_MONTH,
1031 Calendar.WEEK_OF_YEAR, Calendar.WEEK_OF_MONTH,
1032 Calendar.AM_PM, Calendar.HOUR, Calendar.HOUR, Calendar.ZONE_OFFSET,
1033 Calendar.ZONE_OFFSET,
1034 // Pseudo Calendar fields
1035 CalendarBuilder.WEEK_YEAR,
1036 CalendarBuilder.ISO_DAY_OF_WEEK,
1037 Calendar.ZONE_OFFSET
1040 // Map index into pattern character string to DateFormat field number
1041 private static final int[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD = {
1042 DateFormat.ERA_FIELD, DateFormat.YEAR_FIELD, DateFormat.MONTH_FIELD,
1043 DateFormat.DATE_FIELD, DateFormat.HOUR_OF_DAY1_FIELD,
1044 DateFormat.HOUR_OF_DAY0_FIELD, DateFormat.MINUTE_FIELD,
1045 DateFormat.SECOND_FIELD, DateFormat.MILLISECOND_FIELD,
1046 DateFormat.DAY_OF_WEEK_FIELD, DateFormat.DAY_OF_YEAR_FIELD,
1047 DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD, DateFormat.WEEK_OF_YEAR_FIELD,
1048 DateFormat.WEEK_OF_MONTH_FIELD, DateFormat.AM_PM_FIELD,
1049 DateFormat.HOUR1_FIELD, DateFormat.HOUR0_FIELD,
1050 DateFormat.TIMEZONE_FIELD, DateFormat.TIMEZONE_FIELD,
1051 DateFormat.YEAR_FIELD, DateFormat.DAY_OF_WEEK_FIELD,
1052 DateFormat.TIMEZONE_FIELD
1055 // Maps from DecimalFormatSymbols index to Field constant
1056 private static final Field[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID = {
1057 Field.ERA, Field.YEAR, Field.MONTH, Field.DAY_OF_MONTH,
1058 Field.HOUR_OF_DAY1, Field.HOUR_OF_DAY0, Field.MINUTE,
1059 Field.SECOND, Field.MILLISECOND, Field.DAY_OF_WEEK,
1060 Field.DAY_OF_YEAR, Field.DAY_OF_WEEK_IN_MONTH,
1061 Field.WEEK_OF_YEAR, Field.WEEK_OF_MONTH,
1062 Field.AM_PM, Field.HOUR1, Field.HOUR0, Field.TIME_ZONE,
1064 Field.YEAR, Field.DAY_OF_WEEK,
1069 * Private member function that does the real date/time formatting.
1071 private void subFormat(int patternCharIndex, int count,
1072 FieldDelegate delegate, StringBuffer buffer,
1073 boolean useDateFormatSymbols)
1075 int maxIntCount = Integer.MAX_VALUE;
1076 String current = null;
1077 int beginOffset = buffer.length();
1079 int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
1081 if (field == CalendarBuilder.WEEK_YEAR) {
1082 if (calendar.isWeekDateSupported()) {
1083 value = calendar.getWeekYear();
1085 // use calendar year 'y' instead
1086 patternCharIndex = PATTERN_YEAR;
1087 field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
1088 value = calendar.get(field);
1090 } else if (field == CalendarBuilder.ISO_DAY_OF_WEEK) {
1091 value = CalendarBuilder.toISODayOfWeek(calendar.get(Calendar.DAY_OF_WEEK));
1093 value = calendar.get(field);
1096 int style = (count >= 4) ? Calendar.LONG : Calendar.SHORT;
1097 if (!useDateFormatSymbols && field != CalendarBuilder.ISO_DAY_OF_WEEK) {
1098 current = calendar.getDisplayName(field, style, locale);
1101 // Note: zeroPaddingNumber() assumes that maxDigits is either
1102 // 2 or maxIntCount. If we make any changes to this,
1103 // zeroPaddingNumber() must be fixed.
1105 switch (patternCharIndex) {
1106 case PATTERN_ERA: // 'G'
1107 if (useDateFormatSymbols) {
1108 String[] eras = formatData.getEras();
1109 if (value < eras.length)
1110 current = eras[value];
1112 if (current == null)
1116 case PATTERN_WEEK_YEAR: // 'Y'
1117 case PATTERN_YEAR: // 'y'
1118 if (calendar instanceof GregorianCalendar) {
1120 zeroPaddingNumber(value, count, maxIntCount, buffer);
1122 zeroPaddingNumber(value, 2, 2, buffer); // clip 1996 to 96
1124 if (current == null) {
1125 zeroPaddingNumber(value, style == Calendar.LONG ? 1 : count,
1126 maxIntCount, buffer);
1131 case PATTERN_MONTH: // 'M'
1132 if (useDateFormatSymbols) {
1135 months = formatData.getMonths();
1136 current = months[value];
1137 } else if (count == 3) {
1138 months = formatData.getShortMonths();
1139 current = months[value];
1146 if (current == null) {
1147 zeroPaddingNumber(value+1, count, maxIntCount, buffer);
1151 case PATTERN_HOUR_OF_DAY1: // 'k' 1-based. eg, 23:59 + 1 hour =>> 24:59
1152 if (current == null) {
1154 zeroPaddingNumber(calendar.getMaximum(Calendar.HOUR_OF_DAY)+1,
1155 count, maxIntCount, buffer);
1157 zeroPaddingNumber(value, count, maxIntCount, buffer);
1161 case PATTERN_DAY_OF_WEEK: // 'E'
1162 if (useDateFormatSymbols) {
1165 weekdays = formatData.getWeekdays();
1166 current = weekdays[value];
1167 } else { // count < 4, use abbreviated form if exists
1168 weekdays = formatData.getShortWeekdays();
1169 current = weekdays[value];
1174 case PATTERN_AM_PM: // 'a'
1175 if (useDateFormatSymbols) {
1176 String[] ampm = formatData.getAmPmStrings();
1177 current = ampm[value];
1181 case PATTERN_HOUR1: // 'h' 1-based. eg, 11PM + 1 hour =>> 12 AM
1182 if (current == null) {
1184 zeroPaddingNumber(calendar.getLeastMaximum(Calendar.HOUR)+1,
1185 count, maxIntCount, buffer);
1187 zeroPaddingNumber(value, count, maxIntCount, buffer);
1191 case PATTERN_ZONE_NAME: // 'z'
1192 if (current == null) {
1193 if (formatData.locale == null || formatData.isZoneStringsSet) {
1195 formatData.getZoneIndex(calendar.getTimeZone().getID());
1196 if (zoneIndex == -1) {
1197 value = calendar.get(Calendar.ZONE_OFFSET) +
1198 calendar.get(Calendar.DST_OFFSET);
1199 buffer.append(ZoneInfoFile.toCustomID(value));
1201 int index = (calendar.get(Calendar.DST_OFFSET) == 0) ? 1: 3;
1203 // Use the short name
1206 String[][] zoneStrings = formatData.getZoneStringsWrapper();
1207 buffer.append(zoneStrings[zoneIndex][index]);
1210 TimeZone tz = calendar.getTimeZone();
1211 boolean daylight = (calendar.get(Calendar.DST_OFFSET) != 0);
1212 int tzstyle = (count < 4 ? TimeZone.SHORT : TimeZone.LONG);
1213 buffer.append(tz.getDisplayName(daylight, tzstyle, formatData.locale));
1218 case PATTERN_ZONE_VALUE: // 'Z' ("-/+hhmm" form)
1219 value = (calendar.get(Calendar.ZONE_OFFSET) +
1220 calendar.get(Calendar.DST_OFFSET)) / 60000;
1229 int num = (value / 60) * 100 + (value % 60);
1230 CalendarUtils.sprintf0d(buffer, num, width);
1233 case PATTERN_ISO_ZONE: // 'X'
1234 value = calendar.get(Calendar.ZONE_OFFSET)
1235 + calendar.get(Calendar.DST_OFFSET);
1250 CalendarUtils.sprintf0d(buffer, value / 60, 2);
1258 CalendarUtils.sprintf0d(buffer, value % 60, 2);
1262 // case PATTERN_DAY_OF_MONTH: // 'd'
1263 // case PATTERN_HOUR_OF_DAY0: // 'H' 0-based. eg, 23:59 + 1 hour =>> 00:59
1264 // case PATTERN_MINUTE: // 'm'
1265 // case PATTERN_SECOND: // 's'
1266 // case PATTERN_MILLISECOND: // 'S'
1267 // case PATTERN_DAY_OF_YEAR: // 'D'
1268 // case PATTERN_DAY_OF_WEEK_IN_MONTH: // 'F'
1269 // case PATTERN_WEEK_OF_YEAR: // 'w'
1270 // case PATTERN_WEEK_OF_MONTH: // 'W'
1271 // case PATTERN_HOUR0: // 'K' eg, 11PM + 1 hour =>> 0 AM
1272 // case PATTERN_ISO_DAY_OF_WEEK: // 'u' pseudo field, Monday = 1, ..., Sunday = 7
1273 if (current == null) {
1274 zeroPaddingNumber(value, count, maxIntCount, buffer);
1277 } // switch (patternCharIndex)
1279 if (current != null) {
1280 buffer.append(current);
1283 int fieldID = PATTERN_INDEX_TO_DATE_FORMAT_FIELD[patternCharIndex];
1284 Field f = PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID[patternCharIndex];
1286 delegate.formatted(fieldID, f, f, beginOffset, buffer.length(), buffer);
1290 * Formats a number with the specified minimum and maximum number of digits.
1292 private final void zeroPaddingNumber(int value, int minDigits, int maxDigits, StringBuffer buffer)
1294 // Optimization for 1, 2 and 4 digit numbers. This should
1295 // cover most cases of formatting date/time related items.
1296 // Note: This optimization code assumes that maxDigits is
1297 // either 2 or Integer.MAX_VALUE (maxIntCount in format()).
1299 if (zeroDigit == 0) {
1300 zeroDigit = ((DecimalFormat)numberFormat).getDecimalFormatSymbols().getZeroDigit();
1303 if (value < 100 && minDigits >= 1 && minDigits <= 2) {
1305 if (minDigits == 2) {
1306 buffer.append(zeroDigit);
1308 buffer.append((char)(zeroDigit + value));
1310 buffer.append((char)(zeroDigit + value / 10));
1311 buffer.append((char)(zeroDigit + value % 10));
1314 } else if (value >= 1000 && value < 10000) {
1315 if (minDigits == 4) {
1316 buffer.append((char)(zeroDigit + value / 1000));
1318 buffer.append((char)(zeroDigit + value / 100));
1320 buffer.append((char)(zeroDigit + value / 10));
1321 buffer.append((char)(zeroDigit + value % 10));
1324 if (minDigits == 2 && maxDigits == 2) {
1325 zeroPaddingNumber(value % 100, 2, 2, buffer);
1330 } catch (Exception e) {
1333 numberFormat.setMinimumIntegerDigits(minDigits);
1334 numberFormat.setMaximumIntegerDigits(maxDigits);
1335 numberFormat.format((long)value, buffer, DontCareFieldPosition.INSTANCE);
1340 * Parses text from a string to produce a <code>Date</code>.
1342 * The method attempts to parse text starting at the index given by
1344 * If parsing succeeds, then the index of <code>pos</code> is updated
1345 * to the index after the last character used (parsing does not necessarily
1346 * use all characters up to the end of the string), and the parsed
1347 * date is returned. The updated <code>pos</code> can be used to
1348 * indicate the starting point for the next call to this method.
1349 * If an error occurs, then the index of <code>pos</code> is not
1350 * changed, the error index of <code>pos</code> is set to the index of
1351 * the character where the error occurred, and null is returned.
1353 * <p>This parsing operation uses the {@link DateFormat#calendar
1354 * calendar} to produce a {@code Date}. All of the {@code
1355 * calendar}'s date-time fields are {@linkplain Calendar#clear()
1356 * cleared} before parsing, and the {@code calendar}'s default
1357 * values of the date-time fields are used for any missing
1358 * date-time information. For example, the year value of the
1359 * parsed {@code Date} is 1970 with {@link GregorianCalendar} if
1360 * no year value is given from the parsing operation. The {@code
1361 * TimeZone} value may be overwritten, depending on the given
1362 * pattern and the time zone value in {@code text}. Any {@code
1363 * TimeZone} value that has previously been set by a call to
1364 * {@link #setTimeZone(java.util.TimeZone) setTimeZone} may need
1365 * to be restored for further operations.
1367 * @param text A <code>String</code>, part of which should be parsed.
1368 * @param pos A <code>ParsePosition</code> object with index and error
1369 * index information as described above.
1370 * @return A <code>Date</code> parsed from the string. In case of
1371 * error, returns null.
1372 * @exception NullPointerException if <code>text</code> or <code>pos</code> is null.
1374 public Date parse(String text, ParsePosition pos)
1376 checkNegativeNumberExpression();
1378 int start = pos.index;
1379 int oldStart = start;
1380 int textLength = text.length();
1382 boolean[] ambiguousYear = {false};
1384 CalendarBuilder calb = new CalendarBuilder();
1386 for (int i = 0; i < compiledPattern.length; ) {
1387 int tag = compiledPattern[i] >>> 8;
1388 int count = compiledPattern[i++] & 0xff;
1390 count = compiledPattern[i++] << 16;
1391 count |= compiledPattern[i++];
1395 case TAG_QUOTE_ASCII_CHAR:
1396 if (start >= textLength || text.charAt(start) != (char)count) {
1397 pos.index = oldStart;
1398 pos.errorIndex = start;
1404 case TAG_QUOTE_CHARS:
1405 while (count-- > 0) {
1406 if (start >= textLength || text.charAt(start) != compiledPattern[i++]) {
1407 pos.index = oldStart;
1408 pos.errorIndex = start;
1416 // Peek the next pattern to determine if we need to
1417 // obey the number of pattern letters for
1418 // parsing. It's required when parsing contiguous
1419 // digit text (e.g., "20010704") with a pattern which
1420 // has no delimiters between fields, like "yyyyMMdd".
1421 boolean obeyCount = false;
1423 // In Arabic, a minus sign for a negative number is put after
1424 // the number. Even in another locale, a minus sign can be
1425 // put after a number using DateFormat.setNumberFormat().
1426 // If both the minus sign and the field-delimiter are '-',
1427 // subParse() needs to determine whether a '-' after a number
1428 // in the given text is a delimiter or is a minus sign for the
1429 // preceding number. We give subParse() a clue based on the
1430 // information in compiledPattern.
1431 boolean useFollowingMinusSignAsDelimiter = false;
1433 if (i < compiledPattern.length) {
1434 int nextTag = compiledPattern[i] >>> 8;
1435 if (!(nextTag == TAG_QUOTE_ASCII_CHAR ||
1436 nextTag == TAG_QUOTE_CHARS)) {
1440 if (hasFollowingMinusSign &&
1441 (nextTag == TAG_QUOTE_ASCII_CHAR ||
1442 nextTag == TAG_QUOTE_CHARS)) {
1444 if (nextTag == TAG_QUOTE_ASCII_CHAR) {
1445 c = compiledPattern[i] & 0xff;
1447 c = compiledPattern[i+1];
1450 if (c == minusSign) {
1451 useFollowingMinusSignAsDelimiter = true;
1455 start = subParse(text, start, tag, count, obeyCount,
1457 useFollowingMinusSignAsDelimiter, calb);
1459 pos.index = oldStart;
1465 // At this point the fields of Calendar have been set. Calendar
1466 // will fill in default values for missing fields when the time
1473 parsedDate = calb.establish(calendar).getTime();
1474 // If the year value is ambiguous,
1475 // then the two-digit year == the default start year
1476 if (ambiguousYear[0]) {
1477 if (parsedDate.before(defaultCenturyStart)) {
1478 parsedDate = calb.addYear(100).establish(calendar).getTime();
1482 // An IllegalArgumentException will be thrown by Calendar.getTime()
1483 // if any fields are out of range, e.g., MONTH == 17.
1484 catch (IllegalArgumentException e) {
1485 pos.errorIndex = start;
1486 pos.index = oldStart;
1494 * Private code-size reduction function used by subParse.
1495 * @param text the time text being parsed.
1496 * @param start where to start parsing.
1497 * @param field the date field being parsed.
1498 * @param data the string array to parsed.
1499 * @return the new start position if matching succeeded; a negative number
1500 * indicating matching failure, otherwise.
1502 private int matchString(String text, int start, int field, String[] data, CalendarBuilder calb)
1505 int count = data.length;
1507 if (field == Calendar.DAY_OF_WEEK) i = 1;
1509 // There may be multiple strings in the data[] array which begin with
1510 // the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
1511 // We keep track of the longest match, and return that. Note that this
1512 // unfortunately requires us to test all array elements.
1513 int bestMatchLength = 0, bestMatch = -1;
1514 for (; i<count; ++i)
1516 int length = data[i].length();
1517 // Always compare if we have no match yet; otherwise only compare
1518 // against potentially better matches (longer strings).
1519 if (length > bestMatchLength &&
1520 text.regionMatches(true, start, data[i], 0, length))
1523 bestMatchLength = length;
1528 calb.set(field, bestMatch);
1529 return start + bestMatchLength;
1535 * Performs the same thing as matchString(String, int, int,
1536 * String[]). This method takes a Map<String, Integer> instead of
1539 private int matchString(String text, int start, int field,
1540 Map<String,Integer> data, CalendarBuilder calb) {
1542 String bestMatch = null;
1544 for (String name : data.keySet()) {
1545 int length = name.length();
1546 if (bestMatch == null || length > bestMatch.length()) {
1547 if (text.regionMatches(true, start, name, 0, length)) {
1553 if (bestMatch != null) {
1554 calb.set(field, data.get(bestMatch));
1555 return start + bestMatch.length();
1561 private int matchZoneString(String text, int start, String[] zoneNames) {
1562 for (int i = 1; i <= 4; ++i) {
1563 // Checking long and short zones [1 & 2],
1564 // and long and short daylight [3 & 4].
1565 String zoneName = zoneNames[i];
1566 if (text.regionMatches(true, start,
1567 zoneName, 0, zoneName.length())) {
1574 private boolean matchDSTString(String text, int start, int zoneIndex, int standardIndex,
1575 String[][] zoneStrings) {
1576 int index = standardIndex + 2;
1577 String zoneName = zoneStrings[zoneIndex][index];
1578 if (text.regionMatches(true, start,
1579 zoneName, 0, zoneName.length())) {
1586 * find time zone 'text' matched zoneStrings and set to internal
1589 private int subParseZoneString(String text, int start, CalendarBuilder calb) {
1590 boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
1591 TimeZone currentTimeZone = getTimeZone();
1593 // At this point, check for named time zones by looking through
1594 // the locale data from the TimeZoneNames strings.
1595 // Want to be able to parse both short and long forms.
1596 int zoneIndex = formatData.getZoneIndex(currentTimeZone.getID());
1598 String[][] zoneStrings = formatData.getZoneStringsWrapper();
1599 String[] zoneNames = null;
1601 if (zoneIndex != -1) {
1602 zoneNames = zoneStrings[zoneIndex];
1603 if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
1604 if (nameIndex <= 2) {
1605 // Check if the standard name (abbr) and the daylight name are the same.
1606 useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
1608 tz = TimeZone.getTimeZone(zoneNames[0]);
1612 zoneIndex = formatData.getZoneIndex(TimeZone.getDefault().getID());
1613 if (zoneIndex != -1) {
1614 zoneNames = zoneStrings[zoneIndex];
1615 if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
1616 if (nameIndex <= 2) {
1617 useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
1619 tz = TimeZone.getTimeZone(zoneNames[0]);
1625 int len = zoneStrings.length;
1626 for (int i = 0; i < len; i++) {
1627 zoneNames = zoneStrings[i];
1628 if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
1629 if (nameIndex <= 2) {
1630 useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
1632 tz = TimeZone.getTimeZone(zoneNames[0]);
1637 if (tz != null) { // Matched any ?
1638 if (!tz.equals(currentTimeZone)) {
1641 // If the time zone matched uses the same name
1642 // (abbreviation) for both standard and daylight time,
1643 // let the time zone in the Calendar decide which one.
1645 // Also if tz.getDSTSaving() returns 0 for DST, use tz to
1646 // determine the local time. (6645292)
1647 int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
1648 if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
1649 calb.set(Calendar.ZONE_OFFSET, tz.getRawOffset())
1650 .set(Calendar.DST_OFFSET, dstAmount);
1652 return (start + zoneNames[nameIndex].length());
1658 * Parses numeric forms of time zone offset, such as "hh:mm", and
1659 * sets calb to the parsed value.
1661 * @param text the text to be parsed
1662 * @param start the character position to start parsing
1663 * @param sign 1: positive; -1: negative
1664 * @param count 0: 'Z' or "GMT+hh:mm" parsing; 1 - 3: the number of 'X's
1665 * @param colon true - colon required between hh and mm; false - no colon required
1666 * @param calb a CalendarBuilder in which the parsed value is stored
1667 * @return updated parsed position, or its negative value to indicate a parsing error
1669 private int subParseNumericZone(String text, int start, int sign, int count,
1670 boolean colon, CalendarBuilder calb) {
1675 char c = text.charAt(index++);
1682 c = text.charAt(index++);
1684 hours = hours * 10 + (c - '0');
1686 // If no colon in RFC 822 or 'X' (ISO), two digits are
1688 if (count > 0 || !colon) {
1698 // Proceed with parsing mm
1699 c = text.charAt(index++);
1704 c = text.charAt(index++);
1710 c = text.charAt(index++);
1714 minutes = minutes * 10 + (c - '0');
1719 minutes += hours * 60;
1720 calb.set(Calendar.ZONE_OFFSET, minutes * MILLIS_PER_MINUTE * sign)
1721 .set(Calendar.DST_OFFSET, 0);
1723 } catch (IndexOutOfBoundsException e) {
1725 return 1 - index; // -(index - 1)
1728 private boolean isDigit(char c) {
1729 return c >= '0' && c <= '9';
1733 * Private member function that converts the parsed date strings into
1734 * timeFields. Returns -start (for ParsePosition) if failed.
1735 * @param text the time text to be parsed.
1736 * @param start where to start parsing.
1737 * @param ch the pattern character for the date field text to be parsed.
1738 * @param count the count of a pattern character.
1739 * @param obeyCount if true, then the next field directly abuts this one,
1740 * and we should use the count to know when to stop parsing.
1741 * @param ambiguousYear return parameter; upon return, if ambiguousYear[0]
1742 * is true, then a two-digit year was parsed and may need to be readjusted.
1743 * @param origPos origPos.errorIndex is used to return an error index
1744 * at which a parse error occurred, if matching failure occurs.
1745 * @return the new start position if matching succeeded; -1 indicating
1746 * matching failure, otherwise. In case matching failure occurred,
1747 * an error index is set to origPos.errorIndex.
1749 private int subParse(String text, int start, int patternCharIndex, int count,
1750 boolean obeyCount, boolean[] ambiguousYear,
1751 ParsePosition origPos,
1752 boolean useFollowingMinusSignAsDelimiter, CalendarBuilder calb) {
1753 Number number = null;
1755 ParsePosition pos = new ParsePosition(0);
1757 if (patternCharIndex == PATTERN_WEEK_YEAR && !calendar.isWeekDateSupported()) {
1758 // use calendar year 'y' instead
1759 patternCharIndex = PATTERN_YEAR;
1761 int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
1763 // If there are any spaces here, skip over them. If we hit the end
1764 // of the string, then fail.
1766 if (pos.index >= text.length()) {
1767 origPos.errorIndex = start;
1770 char c = text.charAt(pos.index);
1771 if (c != ' ' && c != '\t') break;
1777 // We handle a few special cases here where we need to parse
1778 // a number value. We handle further, more generic cases below. We need
1779 // to handle some of them here because some fields require extra processing on
1780 // the parsed value.
1781 if (patternCharIndex == PATTERN_HOUR_OF_DAY1 ||
1782 patternCharIndex == PATTERN_HOUR1 ||
1783 (patternCharIndex == PATTERN_MONTH && count <= 2) ||
1784 patternCharIndex == PATTERN_YEAR ||
1785 patternCharIndex == PATTERN_WEEK_YEAR) {
1786 // It would be good to unify this with the obeyCount logic below,
1787 // but that's going to be difficult.
1789 if ((start+count) > text.length()) {
1792 number = numberFormat.parse(text.substring(0, start+count), pos);
1794 number = numberFormat.parse(text, pos);
1796 if (number == null) {
1797 if (patternCharIndex != PATTERN_YEAR || calendar instanceof GregorianCalendar) {
1801 value = number.intValue();
1803 if (useFollowingMinusSignAsDelimiter && (value < 0) &&
1804 (((pos.index < text.length()) &&
1805 (text.charAt(pos.index) != minusSign)) ||
1806 ((pos.index == text.length()) &&
1807 (text.charAt(pos.index-1) == minusSign)))) {
1814 boolean useDateFormatSymbols = useDateFormatSymbols();
1817 switch (patternCharIndex) {
1818 case PATTERN_ERA: // 'G'
1819 if (useDateFormatSymbols) {
1820 if ((index = matchString(text, start, Calendar.ERA, formatData.getEras(), calb)) > 0) {
1824 Map<String, Integer> map = calendar.getDisplayNames(field,
1825 Calendar.ALL_STYLES,
1827 if ((index = matchString(text, start, field, map, calb)) > 0) {
1833 case PATTERN_WEEK_YEAR: // 'Y'
1834 case PATTERN_YEAR: // 'y'
1835 if (!(calendar instanceof GregorianCalendar)) {
1836 // calendar might have text representations for year values,
1837 // such as "\u5143" in JapaneseImperialCalendar.
1838 int style = (count >= 4) ? Calendar.LONG : Calendar.SHORT;
1839 Map<String, Integer> map = calendar.getDisplayNames(field, style, locale);
1841 if ((index = matchString(text, start, field, map, calb)) > 0) {
1845 calb.set(field, value);
1849 // If there are 3 or more YEAR pattern characters, this indicates
1850 // that the year value is to be treated literally, without any
1851 // two-digit year adjustments (e.g., from "01" to 2001). Otherwise
1852 // we made adjustments to place the 2-digit year in the proper
1853 // century, for parsed strings from "00" to "99". Any other string
1854 // is treated literally: "2250", "-1", "1", "002".
1855 if (count <= 2 && (pos.index - start) == 2
1856 && Character.isDigit(text.charAt(start))
1857 && Character.isDigit(text.charAt(start+1))) {
1858 // Assume for example that the defaultCenturyStart is 6/18/1903.
1859 // This means that two-digit years will be forced into the range
1860 // 6/18/1903 to 6/17/2003. As a result, years 00, 01, and 02
1861 // correspond to 2000, 2001, and 2002. Years 04, 05, etc. correspond
1862 // to 1904, 1905, etc. If the year is 03, then it is 2003 if the
1863 // other fields specify a date before 6/18, or 1903 if they specify a
1864 // date afterwards. As a result, 03 is an ambiguous year. All other
1865 // two-digit years are unambiguous.
1866 int ambiguousTwoDigitYear = defaultCenturyStartYear % 100;
1867 ambiguousYear[0] = value == ambiguousTwoDigitYear;
1868 value += (defaultCenturyStartYear/100)*100 +
1869 (value < ambiguousTwoDigitYear ? 100 : 0);
1871 calb.set(field, value);
1874 case PATTERN_MONTH: // 'M'
1875 if (count <= 2) // i.e., M or MM.
1877 // Don't want to parse the month if it is a string
1878 // while pattern uses numeric style: M or MM.
1879 // [We computed 'value' above.]
1880 calb.set(Calendar.MONTH, value - 1);
1884 if (useDateFormatSymbols) {
1885 // count >= 3 // i.e., MMM or MMMM
1886 // Want to be able to parse both short and long forms.
1887 // Try count == 4 first:
1889 if ((newStart = matchString(text, start, Calendar.MONTH,
1890 formatData.getMonths(), calb)) > 0) {
1893 // count == 4 failed, now try count == 3
1894 if ((index = matchString(text, start, Calendar.MONTH,
1895 formatData.getShortMonths(), calb)) > 0) {
1899 Map<String, Integer> map = calendar.getDisplayNames(field,
1900 Calendar.ALL_STYLES,
1902 if ((index = matchString(text, start, field, map, calb)) > 0) {
1908 case PATTERN_HOUR_OF_DAY1: // 'k' 1-based. eg, 23:59 + 1 hour =>> 24:59
1910 // Validate the hour value in non-lenient
1911 if (value < 1 || value > 24) {
1915 // [We computed 'value' above.]
1916 if (value == calendar.getMaximum(Calendar.HOUR_OF_DAY)+1)
1918 calb.set(Calendar.HOUR_OF_DAY, value);
1921 case PATTERN_DAY_OF_WEEK: // 'E'
1923 if (useDateFormatSymbols) {
1924 // Want to be able to parse both short and long forms.
1925 // Try count == 4 (DDDD) first:
1927 if ((newStart=matchString(text, start, Calendar.DAY_OF_WEEK,
1928 formatData.getWeekdays(), calb)) > 0) {
1931 // DDDD failed, now try DDD
1932 if ((index = matchString(text, start, Calendar.DAY_OF_WEEK,
1933 formatData.getShortWeekdays(), calb)) > 0) {
1937 int[] styles = { Calendar.LONG, Calendar.SHORT };
1938 for (int style : styles) {
1939 Map<String,Integer> map = calendar.getDisplayNames(field, style, locale);
1940 if ((index = matchString(text, start, field, map, calb)) > 0) {
1948 case PATTERN_AM_PM: // 'a'
1949 if (useDateFormatSymbols) {
1950 if ((index = matchString(text, start, Calendar.AM_PM,
1951 formatData.getAmPmStrings(), calb)) > 0) {
1955 Map<String,Integer> map = calendar.getDisplayNames(field, Calendar.ALL_STYLES, locale);
1956 if ((index = matchString(text, start, field, map, calb)) > 0) {
1962 case PATTERN_HOUR1: // 'h' 1-based. eg, 11PM + 1 hour =>> 12 AM
1964 // Validate the hour value in non-lenient
1965 if (value < 1 || value > 12) {
1969 // [We computed 'value' above.]
1970 if (value == calendar.getLeastMaximum(Calendar.HOUR)+1)
1972 calb.set(Calendar.HOUR, value);
1975 case PATTERN_ZONE_NAME: // 'z'
1976 case PATTERN_ZONE_VALUE: // 'Z'
1980 char c = text.charAt(pos.index);
1983 } else if (c == '-') {
1987 // Try parsing a custom time zone "GMT+hh:mm" or "GMT".
1988 if ((c == 'G' || c == 'g')
1989 && (text.length() - start) >= GMT.length()
1990 && text.regionMatches(true, start, GMT, 0, GMT.length())) {
1991 pos.index = start + GMT.length();
1993 if ((text.length() - pos.index) > 0) {
1994 c = text.charAt(pos.index);
1997 } else if (c == '-') {
2002 if (sign == 0) { /* "GMT" without offset */
2003 calb.set(Calendar.ZONE_OFFSET, 0)
2004 .set(Calendar.DST_OFFSET, 0);
2008 // Parse the rest as "hh:mm"
2009 int i = subParseNumericZone(text, ++pos.index,
2010 sign, 0, true, calb);
2016 // Try parsing the text as a time zone
2017 // name or abbreviation.
2018 int i = subParseZoneString(text, pos.index, calb);
2025 // Parse the rest as "hhmm" (RFC 822)
2026 int i = subParseNumericZone(text, ++pos.index,
2027 sign, 0, false, calb);
2033 } catch (IndexOutOfBoundsException e) {
2038 case PATTERN_ISO_ZONE: // 'X'
2040 if ((text.length() - pos.index) <= 0) {
2045 char c = text.charAt(pos.index);
2047 calb.set(Calendar.ZONE_OFFSET, 0).set(Calendar.DST_OFFSET, 0);
2051 // parse text as "+/-hh[[:]mm]" based on count
2054 } else if (c == '-') {
2060 int i = subParseNumericZone(text, ++pos.index, sign, count,
2070 // case PATTERN_DAY_OF_MONTH: // 'd'
2071 // case PATTERN_HOUR_OF_DAY0: // 'H' 0-based. eg, 23:59 + 1 hour =>> 00:59
2072 // case PATTERN_MINUTE: // 'm'
2073 // case PATTERN_SECOND: // 's'
2074 // case PATTERN_MILLISECOND: // 'S'
2075 // case PATTERN_DAY_OF_YEAR: // 'D'
2076 // case PATTERN_DAY_OF_WEEK_IN_MONTH: // 'F'
2077 // case PATTERN_WEEK_OF_YEAR: // 'w'
2078 // case PATTERN_WEEK_OF_MONTH: // 'W'
2079 // case PATTERN_HOUR0: // 'K' 0-based. eg, 11PM + 1 hour =>> 0 AM
2080 // case PATTERN_ISO_DAY_OF_WEEK: // 'u' (pseudo field);
2082 // Handle "generic" fields
2084 if ((start+count) > text.length()) {
2087 number = numberFormat.parse(text.substring(0, start+count), pos);
2089 number = numberFormat.parse(text, pos);
2091 if (number != null) {
2092 value = number.intValue();
2094 if (useFollowingMinusSignAsDelimiter && (value < 0) &&
2095 (((pos.index < text.length()) &&
2096 (text.charAt(pos.index) != minusSign)) ||
2097 ((pos.index == text.length()) &&
2098 (text.charAt(pos.index-1) == minusSign)))) {
2103 calb.set(field, value);
2111 origPos.errorIndex = pos.index;
2115 private final String getCalendarName() {
2116 return calendar.getClass().getName();
2119 private boolean useDateFormatSymbols() {
2120 if (useDateFormatSymbols) {
2123 return isGregorianCalendar() || locale == null;
2126 private boolean isGregorianCalendar() {
2127 return "java.util.GregorianCalendar".equals(getCalendarName());
2131 * Translates a pattern, mapping each character in the from string to the
2132 * corresponding character in the to string.
2134 * @exception IllegalArgumentException if the given pattern is invalid
2136 private String translatePattern(String pattern, String from, String to) {
2137 StringBuilder result = new StringBuilder();
2138 boolean inQuote = false;
2139 for (int i = 0; i < pattern.length(); ++i) {
2140 char c = pattern.charAt(i);
2148 else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
2149 int ci = from.indexOf(c);
2151 // patternChars is longer than localPatternChars due
2152 // to serialization compatibility. The pattern letters
2153 // unsupported by localPatternChars pass through.
2154 if (ci < to.length()) {
2158 throw new IllegalArgumentException("Illegal pattern " +
2167 throw new IllegalArgumentException("Unfinished quote in pattern");
2168 return result.toString();
2172 * Returns a pattern string describing this date format.
2174 * @return a pattern string describing this date format.
2176 public String toPattern() {
2181 * Returns a localized pattern string describing this date format.
2183 * @return a localized pattern string describing this date format.
2185 public String toLocalizedPattern() {
2186 return translatePattern(pattern,
2187 DateFormatSymbols.patternChars,
2188 formatData.getLocalPatternChars());
2192 * Applies the given pattern string to this date format.
2194 * @param pattern the new date and time pattern for this date format
2195 * @exception NullPointerException if the given pattern is null
2196 * @exception IllegalArgumentException if the given pattern is invalid
2198 public void applyPattern(String pattern)
2200 compiledPattern = compile(pattern);
2201 this.pattern = pattern;
2205 * Applies the given localized pattern string to this date format.
2207 * @param pattern a String to be mapped to the new date and time format
2208 * pattern for this format
2209 * @exception NullPointerException if the given pattern is null
2210 * @exception IllegalArgumentException if the given pattern is invalid
2212 public void applyLocalizedPattern(String pattern) {
2213 String p = translatePattern(pattern,
2214 formatData.getLocalPatternChars(),
2215 DateFormatSymbols.patternChars);
2216 compiledPattern = compile(p);
2221 * Gets a copy of the date and time format symbols of this date format.
2223 * @return the date and time format symbols of this date format
2224 * @see #setDateFormatSymbols
2226 public DateFormatSymbols getDateFormatSymbols()
2228 return (DateFormatSymbols)formatData.clone();
2232 * Sets the date and time format symbols of this date format.
2234 * @param newFormatSymbols the new date and time format symbols
2235 * @exception NullPointerException if the given newFormatSymbols is null
2236 * @see #getDateFormatSymbols
2238 public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols)
2240 this.formatData = (DateFormatSymbols)newFormatSymbols.clone();
2241 useDateFormatSymbols = true;
2245 * Creates a copy of this <code>SimpleDateFormat</code>. This also
2246 * clones the format's date format symbols.
2248 * @return a clone of this <code>SimpleDateFormat</code>
2250 public Object clone() {
2251 SimpleDateFormat other = (SimpleDateFormat) super.clone();
2252 other.formatData = (DateFormatSymbols) formatData.clone();
2257 * Returns the hash code value for this <code>SimpleDateFormat</code> object.
2259 * @return the hash code value for this <code>SimpleDateFormat</code> object.
2261 public int hashCode()
2263 return pattern.hashCode();
2264 // just enough fields for a reasonable distribution
2268 * Compares the given object with this <code>SimpleDateFormat</code> for
2271 * @return true if the given object is equal to this
2272 * <code>SimpleDateFormat</code>
2274 public boolean equals(Object obj)
2276 if (!super.equals(obj)) return false; // super does class check
2277 SimpleDateFormat that = (SimpleDateFormat) obj;
2278 return (pattern.equals(that.pattern)
2279 && formatData.equals(that.formatData));
2283 * After reading an object from the input stream, the format
2284 * pattern in the object is verified.
2286 * @exception InvalidObjectException if the pattern is invalid
2288 private void readObject(ObjectInputStream stream)
2289 throws IOException, ClassNotFoundException {
2290 stream.defaultReadObject();
2293 compiledPattern = compile(pattern);
2294 } catch (Exception e) {
2295 throw new InvalidObjectException("invalid pattern");
2298 if (serialVersionOnStream < 1) {
2299 // didn't have defaultCenturyStart field
2300 initializeDefaultCentury();
2303 // fill in dependent transient field
2304 parseAmbiguousDatesAsAfter(defaultCenturyStart);
2306 serialVersionOnStream = currentSerialVersion;
2308 // If the deserialized object has a SimpleTimeZone, try
2309 // to replace it with a ZoneInfo equivalent in order to
2310 // be compatible with the SimpleTimeZone-based
2311 // implementation as much as possible.
2312 TimeZone tz = getTimeZone();
2313 if (tz instanceof SimpleTimeZone) {
2314 String id = tz.getID();
2315 TimeZone zi = TimeZone.getTimeZone(id);
2316 if (zi != null && zi.hasSameRules(tz) && zi.getID().equals(id)) {
2323 * Analyze the negative subpattern of DecimalFormat and set/update values
2326 private void checkNegativeNumberExpression() {
2327 if ((numberFormat instanceof DecimalFormat) &&
2328 !numberFormat.equals(originalNumberFormat)) {
2329 String numberPattern = ((DecimalFormat)numberFormat).toPattern();
2330 if (!numberPattern.equals(originalNumberPattern)) {
2331 hasFollowingMinusSign = false;
2333 int separatorIndex = numberPattern.indexOf(';');
2334 // If the negative subpattern is not absent, we have to analayze
2335 // it in order to check if it has a following minus sign.
2336 if (separatorIndex > -1) {
2337 int minusIndex = numberPattern.indexOf('-', separatorIndex);
2338 if ((minusIndex > numberPattern.lastIndexOf('0')) &&
2339 (minusIndex > numberPattern.lastIndexOf('#'))) {
2340 hasFollowingMinusSign = true;
2341 minusSign = ((DecimalFormat)numberFormat).getDecimalFormatSymbols().getMinusSign();
2344 originalNumberPattern = numberPattern;
2346 originalNumberFormat = numberFormat;