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