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