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