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