1. /*
  2. * @(#)SimpleDateFormat.java 1.77 04/01/22
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. /*
  8. * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
  9. * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
  10. *
  11. * The original version of this source code and documentation is copyrighted
  12. * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  13. * materials are provided under terms of a License Agreement between Taligent
  14. * and Sun. This technology is protected by multiple US and International
  15. * patents. This notice and attribution to Taligent may not be removed.
  16. * Taligent is a registered trademark of Taligent, Inc.
  17. *
  18. */
  19. package java.text;
  20. import java.util.TimeZone;
  21. import java.util.Calendar;
  22. import java.util.Date;
  23. import java.util.Locale;
  24. import java.util.ResourceBundle;
  25. import java.util.SimpleTimeZone;
  26. import java.util.GregorianCalendar;
  27. import java.io.ObjectInputStream;
  28. import java.io.InvalidObjectException;
  29. import java.io.IOException;
  30. import java.lang.ClassNotFoundException;
  31. import java.util.Hashtable;
  32. import java.lang.StringIndexOutOfBoundsException;
  33. import sun.text.resources.LocaleData;
  34. import sun.util.calendar.CalendarUtils;
  35. import sun.util.calendar.ZoneInfoFile;
  36. /**
  37. * <code>SimpleDateFormat</code> is a concrete class for formatting and
  38. * parsing dates in a locale-sensitive manner. It allows for formatting
  39. * (date -> text), parsing (text -> date), and normalization.
  40. *
  41. * <p>
  42. * <code>SimpleDateFormat</code> allows you to start by choosing
  43. * any user-defined patterns for date-time formatting. However, you
  44. * are encouraged to create a date-time formatter with either
  45. * <code>getTimeInstance</code>, <code>getDateInstance</code>, or
  46. * <code>getDateTimeInstance</code> in <code>DateFormat</code>. Each
  47. * of these class methods can return a date/time formatter initialized
  48. * with a default format pattern. You may modify the format pattern
  49. * using the <code>applyPattern</code> methods as desired.
  50. * For more information on using these methods, see
  51. * {@link DateFormat}.
  52. *
  53. * <h4>Date and Time Patterns</h4>
  54. * <p>
  55. * Date and time formats are specified by <em>date and time pattern</em>
  56. * strings.
  57. * Within date and time pattern strings, unquoted letters from
  58. * <code>'A'</code> to <code>'Z'</code> and from <code>'a'</code> to
  59. * <code>'z'</code> are interpreted as pattern letters representing the
  60. * components of a date or time string.
  61. * Text can be quoted using single quotes (<code>'</code>) to avoid
  62. * interpretation.
  63. * <code>"''"</code> represents a single quote.
  64. * All other characters are not interpreted; they're simply copied into the
  65. * output string during formatting or matched against the input string
  66. * during parsing.
  67. * <p>
  68. * The following pattern letters are defined (all other characters from
  69. * <code>'A'</code> to <code>'Z'</code> and from <code>'a'</code> to
  70. * <code>'z'</code> are reserved):
  71. * <blockquote>
  72. * <table border=0 cellspacing=3 cellpadding=0 summary="Chart shows pattern letters, date/time component, presentation, and examples.">
  73. * <tr bgcolor="#ccccff">
  74. * <th align=left>Letter
  75. * <th align=left>Date or Time Component
  76. * <th align=left>Presentation
  77. * <th align=left>Examples
  78. * <tr>
  79. * <td><code>G</code>
  80. * <td>Era designator
  81. * <td><a href="#text">Text</a>
  82. * <td><code>AD</code>
  83. * <tr bgcolor="#eeeeff">
  84. * <td><code>y</code>
  85. * <td>Year
  86. * <td><a href="#year">Year</a>
  87. * <td><code>1996</code> <code>96</code>
  88. * <tr>
  89. * <td><code>M</code>
  90. * <td>Month in year
  91. * <td><a href="#month">Month</a>
  92. * <td><code>July</code> <code>Jul</code> <code>07</code>
  93. * <tr bgcolor="#eeeeff">
  94. * <td><code>w</code>
  95. * <td>Week in year
  96. * <td><a href="#number">Number</a>
  97. * <td><code>27</code>
  98. * <tr>
  99. * <td><code>W</code>
  100. * <td>Week in month
  101. * <td><a href="#number">Number</a>
  102. * <td><code>2</code>
  103. * <tr bgcolor="#eeeeff">
  104. * <td><code>D</code>
  105. * <td>Day in year
  106. * <td><a href="#number">Number</a>
  107. * <td><code>189</code>
  108. * <tr>
  109. * <td><code>d</code>
  110. * <td>Day in month
  111. * <td><a href="#number">Number</a>
  112. * <td><code>10</code>
  113. * <tr bgcolor="#eeeeff">
  114. * <td><code>F</code>
  115. * <td>Day of week in month
  116. * <td><a href="#number">Number</a>
  117. * <td><code>2</code>
  118. * <tr>
  119. * <td><code>E</code>
  120. * <td>Day in week
  121. * <td><a href="#text">Text</a>
  122. * <td><code>Tuesday</code> <code>Tue</code>
  123. * <tr bgcolor="#eeeeff">
  124. * <td><code>a</code>
  125. * <td>Am/pm marker
  126. * <td><a href="#text">Text</a>
  127. * <td><code>PM</code>
  128. * <tr>
  129. * <td><code>H</code>
  130. * <td>Hour in day (0-23)
  131. * <td><a href="#number">Number</a>
  132. * <td><code>0</code>
  133. * <tr bgcolor="#eeeeff">
  134. * <td><code>k</code>
  135. * <td>Hour in day (1-24)
  136. * <td><a href="#number">Number</a>
  137. * <td><code>24</code>
  138. * <tr>
  139. * <td><code>K</code>
  140. * <td>Hour in am/pm (0-11)
  141. * <td><a href="#number">Number</a>
  142. * <td><code>0</code>
  143. * <tr bgcolor="#eeeeff">
  144. * <td><code>h</code>
  145. * <td>Hour in am/pm (1-12)
  146. * <td><a href="#number">Number</a>
  147. * <td><code>12</code>
  148. * <tr>
  149. * <td><code>m</code>
  150. * <td>Minute in hour
  151. * <td><a href="#number">Number</a>
  152. * <td><code>30</code>
  153. * <tr bgcolor="#eeeeff">
  154. * <td><code>s</code>
  155. * <td>Second in minute
  156. * <td><a href="#number">Number</a>
  157. * <td><code>55</code>
  158. * <tr>
  159. * <td><code>S</code>
  160. * <td>Millisecond
  161. * <td><a href="#number">Number</a>
  162. * <td><code>978</code>
  163. * <tr bgcolor="#eeeeff">
  164. * <td><code>z</code>
  165. * <td>Time zone
  166. * <td><a href="#timezone">General time zone</a>
  167. * <td><code>Pacific Standard Time</code> <code>PST</code> <code>GMT-08:00</code>
  168. * <tr>
  169. * <td><code>Z</code>
  170. * <td>Time zone
  171. * <td><a href="#rfc822timezone">RFC 822 time zone</a>
  172. * <td><code>-0800</code>
  173. * </table>
  174. * </blockquote>
  175. * Pattern letters are usually repeated, as their number determines the
  176. * exact presentation:
  177. * <ul>
  178. * <li><strong><a name="text">Text:</a></strong>
  179. * For formatting, if the number of pattern letters is 4 or more,
  180. * the full form is used; otherwise a short or abbreviated form
  181. * is used if available.
  182. * For parsing, both forms are accepted, independent of the number
  183. * of pattern letters.
  184. * <li><strong><a name="number">Number:</a></strong>
  185. * For formatting, the number of pattern letters is the minimum
  186. * number of digits, and shorter numbers are zero-padded to this amount.
  187. * For parsing, the number of pattern letters is ignored unless
  188. * it's needed to separate two adjacent fields.
  189. * <li><strong><a name="year">Year:</a></strong>
  190. * For formatting, if the number of pattern letters is 2, the year
  191. * is truncated to 2 digits; otherwise it is interpreted as a
  192. * <a href="#number">number</a>.
  193. * <p>For parsing, if the number of pattern letters is more than 2,
  194. * the year is interpreted literally, regardless of the number of
  195. * digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to
  196. * Jan 11, 12 A.D.
  197. * <p>For parsing with the abbreviated year pattern ("y" or "yy"),
  198. * <code>SimpleDateFormat</code> must interpret the abbreviated year
  199. * relative to some century. It does this by adjusting dates to be
  200. * within 80 years before and 20 years after the time the <code>SimpleDateFormat</code>
  201. * instance is created. For example, using a pattern of "MM/dd/yy" and a
  202. * <code>SimpleDateFormat</code> instance created on Jan 1, 1997, the string
  203. * "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64"
  204. * would be interpreted as May 4, 1964.
  205. * During parsing, only strings consisting of exactly two digits, as defined by
  206. * {@link Character#isDigit(char)}, will be parsed into the default century.
  207. * Any other numeric string, such as a one digit string, a three or more digit
  208. * string, or a two digit string that isn't all digits (for example, "-1"), is
  209. * interpreted literally. So "01/02/3" or "01/02/003" are parsed, using the
  210. * same pattern, as Jan 2, 3 AD. Likewise, "01/02/-3" is parsed as Jan 2, 4 BC.
  211. * <li><strong><a name="month">Month:</a></strong>
  212. * If the number of pattern letters is 3 or more, the month is
  213. * interpreted as <a href="#text">text</a> otherwise,
  214. * it is interpreted as a <a href="#number">number</a>.
  215. * <li><strong><a name="timezone">General time zone:</a></strong>
  216. * Time zones are interpreted as <a href="#text">text</a> if they have
  217. * names. For time zones representing a GMT offset value, the
  218. * following syntax is used:
  219. * <pre>
  220. * <a name="GMTOffsetTimeZone"><i>GMTOffsetTimeZone:</i></a>
  221. * <code>GMT</code> <i>Sign</i> <i>Hours</i> <code>:</code> <i>Minutes</i>
  222. * <i>Sign:</i> one of
  223. * <code>+ -</code>
  224. * <i>Hours:</i>
  225. * <i>Digit</i>
  226. * <i>Digit</i> <i>Digit</i>
  227. * <i>Minutes:</i>
  228. * <i>Digit</i> <i>Digit</i>
  229. * <i>Digit:</i> one of
  230. * <code>0 1 2 3 4 5 6 7 8 9</code></pre>
  231. * <i>Hours</i> must be between 0 and 23, and <i>Minutes</i> must be between
  232. * 00 and 59. The format is locale independent and digits must be taken
  233. * from the Basic Latin block of the Unicode standard.
  234. * <p>For parsing, <a href="#rfc822timezone">RFC 822 time zones</a> are also
  235. * accepted.
  236. * <li><strong><a name="rfc822timezone">RFC 822 time zone:</a></strong>
  237. * For formatting, the RFC 822 4-digit time zone format is used:
  238. * <pre>
  239. * <i>RFC822TimeZone:</i>
  240. * <i>Sign</i> <i>TwoDigitHours</i> <i>Minutes</i>
  241. * <i>TwoDigitHours:</i>
  242. * <i>Digit Digit</i></pre>
  243. * <i>TwoDigitHours</i> must be between 00 and 23. Other definitions
  244. * are as for <a href="#timezone">general time zones</a>.
  245. * <p>For parsing, <a href="#timezone">general time zones</a> are also
  246. * accepted.
  247. * </ul>
  248. * <code>SimpleDateFormat</code> also supports <em>localized date and time
  249. * pattern</em> strings. In these strings, the pattern letters described above
  250. * may be replaced with other, locale dependent, pattern letters.
  251. * <code>SimpleDateFormat</code> does not deal with the localization of text
  252. * other than the pattern letters; that's up to the client of the class.
  253. * <p>
  254. *
  255. * <h4>Examples</h4>
  256. *
  257. * The following examples show how date and time patterns are interpreted in
  258. * the U.S. locale. The given date and time are 2001-07-04 12:08:56 local time
  259. * in the U.S. Pacific Time time zone.
  260. * <blockquote>
  261. * <table border=0 cellspacing=3 cellpadding=0 summary="Examples of date and time patterns interpreted in the U.S. locale">
  262. * <tr bgcolor="#ccccff">
  263. * <th align=left>Date and Time Pattern
  264. * <th align=left>Result
  265. * <tr>
  266. * <td><code>"yyyy.MM.dd G 'at' HH:mm:ss z"</code>
  267. * <td><code>2001.07.04 AD at 12:08:56 PDT</code>
  268. * <tr bgcolor="#eeeeff">
  269. * <td><code>"EEE, MMM d, ''yy"</code>
  270. * <td><code>Wed, Jul 4, '01</code>
  271. * <tr>
  272. * <td><code>"h:mm a"</code>
  273. * <td><code>12:08 PM</code>
  274. * <tr bgcolor="#eeeeff">
  275. * <td><code>"hh 'o''clock' a, zzzz"</code>
  276. * <td><code>12 o'clock PM, Pacific Daylight Time</code>
  277. * <tr>
  278. * <td><code>"K:mm a, z"</code>
  279. * <td><code>0:08 PM, PDT</code>
  280. * <tr bgcolor="#eeeeff">
  281. * <td><code>"yyyyy.MMMMM.dd GGG hh:mm aaa"</code>
  282. * <td><code>02001.July.04 AD 12:08 PM</code>
  283. * <tr>
  284. * <td><code>"EEE, d MMM yyyy HH:mm:ss Z"</code>
  285. * <td><code>Wed, 4 Jul 2001 12:08:56 -0700</code>
  286. * <tr bgcolor="#eeeeff">
  287. * <td><code>"yyMMddHHmmssZ"</code>
  288. * <td><code>010704120856-0700</code>
  289. * <tr>
  290. * <td><code>"yyyy-MM-dd'T'HH:mm:ss.SSSZ"</code>
  291. * <td><code>2001-07-04T12:08:56.235-0700</code>
  292. * </table>
  293. * </blockquote>
  294. *
  295. * <h4><a name="synchronization">Synchronization</a></h4>
  296. *
  297. * <p>
  298. * Date formats are not synchronized.
  299. * It is recommended to create separate format instances for each thread.
  300. * If multiple threads access a format concurrently, it must be synchronized
  301. * externally.
  302. *
  303. * @see <a href="http://java.sun.com/docs/books/tutorial/i18n/format/simpleDateFormat.html">Java Tutorial</a>
  304. * @see java.util.Calendar
  305. * @see java.util.TimeZone
  306. * @see DateFormat
  307. * @see DateFormatSymbols
  308. * @version 1.77, 01/22/04
  309. * @author Mark Davis, Chen-Lieh Huang, Alan Liu
  310. */
  311. public class SimpleDateFormat extends DateFormat {
  312. // the official serial version ID which says cryptically
  313. // which version we're compatible with
  314. static final long serialVersionUID = 4774881970558875024L;
  315. // the internal serial version which says which version was written
  316. // - 0 (default) for version up to JDK 1.1.3
  317. // - 1 for version from JDK 1.1.4, which includes a new field
  318. static final int currentSerialVersion = 1;
  319. /**
  320. * The version of the serialized data on the stream. Possible values:
  321. * <ul>
  322. * <li><b>0</b> or not present on stream: JDK 1.1.3. This version
  323. * has no <code>defaultCenturyStart</code> on stream.
  324. * <li><b>1</b> JDK 1.1.4 or later. This version adds
  325. * <code>defaultCenturyStart</code>.
  326. * </ul>
  327. * When streaming out this class, the most recent format
  328. * and the highest allowable <code>serialVersionOnStream</code>
  329. * is written.
  330. * @serial
  331. * @since JDK1.1.4
  332. */
  333. private int serialVersionOnStream = currentSerialVersion;
  334. /**
  335. * The pattern string of this formatter. This is always a non-localized
  336. * pattern. May not be null. See class documentation for details.
  337. * @serial
  338. */
  339. private String pattern;
  340. /**
  341. * The compiled pattern.
  342. */
  343. transient private char[] compiledPattern;
  344. /**
  345. * Tags for the compiled pattern.
  346. */
  347. private final static int TAG_QUOTE_ASCII_CHAR = 100;
  348. private final static int TAG_QUOTE_CHARS = 101;
  349. /**
  350. * Locale dependent digit zero.
  351. * @see #zeroPaddingNumber
  352. * @see java.text.DecimalFormatSymbols#getZeroDigit
  353. */
  354. transient private char zeroDigit;
  355. /**
  356. * The symbols used by this formatter for week names, month names,
  357. * etc. May not be null.
  358. * @serial
  359. * @see java.text.DateFormatSymbols
  360. */
  361. private DateFormatSymbols formatData;
  362. /**
  363. * We map dates with two-digit years into the century starting at
  364. * <code>defaultCenturyStart</code>, which may be any date. May
  365. * not be null.
  366. * @serial
  367. * @since JDK1.1.4
  368. */
  369. private Date defaultCenturyStart;
  370. transient private int defaultCenturyStartYear;
  371. private static final int millisPerHour = 60 * 60 * 1000;
  372. private static final int millisPerMinute = 60 * 1000;
  373. // For time zones that have no names, use strings GMT+minutes and
  374. // GMT-minutes. For instance, in France the time zone is GMT+60.
  375. private static final String GMT = "GMT";
  376. /**
  377. * Cache to hold the DateTimePatterns of a Locale.
  378. */
  379. private static Hashtable cachedLocaleData = new Hashtable(3);
  380. /**
  381. * Cache NumberFormat instances with Locale key.
  382. */
  383. private static Hashtable cachedNumberFormatData = new Hashtable(3);
  384. /**
  385. * Constructs a <code>SimpleDateFormat</code> using the default pattern and
  386. * date format symbols for the default locale.
  387. * <b>Note:</b> This constructor may not support all locales.
  388. * For full coverage, use the factory methods in the {@link DateFormat}
  389. * class.
  390. */
  391. public SimpleDateFormat() {
  392. this(SHORT, SHORT, Locale.getDefault());
  393. }
  394. /**
  395. * Constructs a <code>SimpleDateFormat</code> using the given pattern and
  396. * the default date format symbols for the default locale.
  397. * <b>Note:</b> This constructor may not support all locales.
  398. * For full coverage, use the factory methods in the {@link DateFormat}
  399. * class.
  400. *
  401. * @param pattern the pattern describing the date and time format
  402. * @exception NullPointerException if the given pattern is null
  403. * @exception IllegalArgumentException if the given pattern is invalid
  404. */
  405. public SimpleDateFormat(String pattern)
  406. {
  407. this(pattern, Locale.getDefault());
  408. }
  409. /**
  410. * Constructs a <code>SimpleDateFormat</code> using the given pattern and
  411. * the default date format symbols for the given locale.
  412. * <b>Note:</b> This constructor may not support all locales.
  413. * For full coverage, use the factory methods in the {@link DateFormat}
  414. * class.
  415. *
  416. * @param pattern the pattern describing the date and time format
  417. * @param locale the locale whose date format symbols should be used
  418. * @exception NullPointerException if the given pattern is null
  419. * @exception IllegalArgumentException if the given pattern is invalid
  420. */
  421. public SimpleDateFormat(String pattern, Locale locale)
  422. {
  423. this.pattern = pattern;
  424. this.formatData = new DateFormatSymbols(locale);
  425. initialize(locale);
  426. }
  427. /**
  428. * Constructs a <code>SimpleDateFormat</code> using the given pattern and
  429. * date format symbols.
  430. *
  431. * @param pattern the pattern describing the date and time format
  432. * @param formatSymbols the date format symbols to be used for formatting
  433. * @exception NullPointerException if the given pattern or formatSymbols is null
  434. * @exception IllegalArgumentException if the given pattern is invalid
  435. */
  436. public SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)
  437. {
  438. this.pattern = pattern;
  439. this.formatData = (DateFormatSymbols) formatSymbols.clone();
  440. initialize(Locale.getDefault());
  441. }
  442. /* Package-private, called by DateFormat factory methods */
  443. SimpleDateFormat(int timeStyle, int dateStyle, Locale loc) {
  444. /* try the cache first */
  445. String[] dateTimePatterns = (String[]) cachedLocaleData.get(loc);
  446. if (dateTimePatterns == null) { /* cache miss */
  447. ResourceBundle r = LocaleData.getLocaleElements(loc);
  448. dateTimePatterns = r.getStringArray("DateTimePatterns");
  449. /* update cache */
  450. cachedLocaleData.put(loc, dateTimePatterns);
  451. }
  452. formatData = new DateFormatSymbols(loc);
  453. if ((timeStyle >= 0) && (dateStyle >= 0)) {
  454. Object[] dateTimeArgs = {dateTimePatterns[timeStyle],
  455. dateTimePatterns[dateStyle + 4]};
  456. pattern = MessageFormat.format(dateTimePatterns[8], dateTimeArgs);
  457. }
  458. else if (timeStyle >= 0) {
  459. pattern = dateTimePatterns[timeStyle];
  460. }
  461. else if (dateStyle >= 0) {
  462. pattern = dateTimePatterns[dateStyle + 4];
  463. }
  464. else {
  465. throw new IllegalArgumentException("No date or time style specified");
  466. }
  467. initialize(loc);
  468. }
  469. /* Initialize calendar and numberFormat fields */
  470. private void initialize(Locale loc) {
  471. // Verify and compile the given pattern.
  472. compiledPattern = compile(pattern);
  473. // The format object must be constructed using the symbols for this zone.
  474. // However, the calendar should use the current default TimeZone.
  475. // If this is not contained in the locale zone strings, then the zone
  476. // will be formatted using generic GMT+/-H:MM nomenclature.
  477. calendar = Calendar.getInstance(TimeZone.getDefault(), loc);
  478. /* try the cache first */
  479. numberFormat = (NumberFormat) cachedNumberFormatData.get(loc);
  480. if (numberFormat == null) { /* cache miss */
  481. numberFormat = NumberFormat.getIntegerInstance(loc);
  482. numberFormat.setGroupingUsed(false);
  483. /* update cache */
  484. cachedNumberFormatData.put(loc, numberFormat);
  485. }
  486. numberFormat = (NumberFormat) numberFormat.clone();
  487. initializeDefaultCentury();
  488. }
  489. /**
  490. * Returns the compiled form of the given pattern. The syntax of
  491. * the compiled pattern is:
  492. * <blockquote>
  493. * CompiledPattern:
  494. * EntryList
  495. * EntryList:
  496. * Entry
  497. * EntryList Entry
  498. * Entry:
  499. * TagField
  500. * TagField data
  501. * TagField:
  502. * Tag Length
  503. * TaggedData
  504. * Tag:
  505. * pattern_char_index
  506. * TAG_QUOTE_CHARS
  507. * Length:
  508. * short_length
  509. * long_length
  510. * TaggedData:
  511. * TAG_QUOTE_ASCII_CHAR ascii_char
  512. *
  513. * </blockquote>
  514. *
  515. * where `short_length' is an 8-bit unsigned integer between 0 and
  516. * 254. `long_length' is a sequence of an 8-bit integer 255 and a
  517. * 32-bit signed integer value which is split into upper and lower
  518. * 16-bit fields in two char's. `pattern_char_index' is an 8-bit
  519. * integer between 0 and 18. `ascii_char' is an 7-bit ASCII
  520. * character value. `data' depends on its Tag value.
  521. * <p>
  522. * If Length is short_length, Tag and short_length are packed in a
  523. * single char, as illustrated below.
  524. * <blockquote>
  525. * char[0] = (Tag << 8) | short_length;
  526. * </blockquote>
  527. *
  528. * If Length is long_length, Tag and 255 are packed in the first
  529. * char and a 32-bit integer, as illustrated below.
  530. * <blockquote>
  531. * char[0] = (Tag << 8) | 255;
  532. * char[1] = (char) (long_length >>> 16);
  533. * char[2] = (char) (long_length & 0xffff);
  534. * </blockquote>
  535. * <p>
  536. * If Tag is a pattern_char_index, its Length is the number of
  537. * pattern characters. For example, if the given pattern is
  538. * "yyyy", Tag is 1 and Length is 4, followed by no data.
  539. * <p>
  540. * If Tag is TAG_QUOTE_CHARS, its Length is the number of char's
  541. * following the TagField. For example, if the given pattern is
  542. * "'o''clock'", Length is 7 followed by a char sequence of
  543. * <code>o&nbs;'&nbs;c&nbs;l&nbs;o&nbs;c&nbs;k</code>.
  544. * <p>
  545. * TAG_QUOTE_ASCII_CHAR is a special tag and has an ASCII
  546. * character in place of Length. For example, if the given pattern
  547. * is "'o'", the TaggedData entry is
  548. * <code>((TAG_QUOTE_ASCII_CHAR&nbs;<<&nbs;8)&nbs;|&nbs;'o')</code>.
  549. *
  550. * @exception NullPointerException if the given pattern is null
  551. * @exception IllegalArgumentException if the given pattern is invalid
  552. */
  553. private char[] compile(String pattern) {
  554. int length = pattern.length();
  555. boolean inQuote = false;
  556. StringBuilder compiledPattern = new StringBuilder(length * 2);
  557. StringBuilder tmpBuffer = null;
  558. int count = 0;
  559. int lastTag = -1;
  560. for (int i = 0; i < length; i++) {
  561. char c = pattern.charAt(i);
  562. if (c == '\'') {
  563. // '' is treated as a single quote regardless of being
  564. // in a quoted section.
  565. if ((i + 1) < length) {
  566. c = pattern.charAt(i + 1);
  567. if (c == '\'') {
  568. i++;
  569. if (count != 0) {
  570. encode(lastTag, count, compiledPattern);
  571. lastTag = -1;
  572. count = 0;
  573. }
  574. if (inQuote) {
  575. tmpBuffer.append(c);
  576. } else {
  577. compiledPattern.append((char)(TAG_QUOTE_ASCII_CHAR << 8 | c));
  578. }
  579. continue;
  580. }
  581. }
  582. if (!inQuote) {
  583. if (count != 0) {
  584. encode(lastTag, count, compiledPattern);
  585. lastTag = -1;
  586. count = 0;
  587. }
  588. if (tmpBuffer == null) {
  589. tmpBuffer = new StringBuilder(length);
  590. } else {
  591. tmpBuffer.setLength(0);
  592. }
  593. inQuote = true;
  594. } else {
  595. int len = tmpBuffer.length();
  596. if (len == 1) {
  597. char ch = tmpBuffer.charAt(0);
  598. if (ch < 128) {
  599. compiledPattern.append((char)(TAG_QUOTE_ASCII_CHAR << 8 | ch));
  600. } else {
  601. compiledPattern.append((char)(TAG_QUOTE_CHARS << 8 | 1));
  602. compiledPattern.append(ch);
  603. }
  604. } else {
  605. encode(TAG_QUOTE_CHARS, len, compiledPattern);
  606. compiledPattern.append(tmpBuffer);
  607. }
  608. inQuote = false;
  609. }
  610. continue;
  611. }
  612. if (inQuote) {
  613. tmpBuffer.append(c);
  614. continue;
  615. }
  616. if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
  617. if (count != 0) {
  618. encode(lastTag, count, compiledPattern);
  619. lastTag = -1;
  620. count = 0;
  621. }
  622. if (c < 128) {
  623. // In most cases, c would be a delimiter, such as ':'.
  624. compiledPattern.append((char)(TAG_QUOTE_ASCII_CHAR << 8 | c));
  625. } else {
  626. // Take any contiguous non-ASCII alphabet characters and
  627. // put them in a single TAG_QUOTE_CHARS.
  628. int j;
  629. for (j = i + 1; j < length; j++) {
  630. char d = pattern.charAt(j);
  631. if (d == '\'' || (d >= 'a' && d <= 'z' || d >= 'A' && d <= 'Z')) {
  632. break;
  633. }
  634. }
  635. compiledPattern.append((char)(TAG_QUOTE_CHARS << 8 | (j - i)));
  636. for (; i < j; i++) {
  637. compiledPattern.append(pattern.charAt(i));
  638. }
  639. i--;
  640. }
  641. continue;
  642. }
  643. int tag;
  644. if ((tag = formatData.patternChars.indexOf(c)) == -1) {
  645. throw new IllegalArgumentException("Illegal pattern character " +
  646. "'" + c + "'");
  647. }
  648. if (lastTag == -1 || lastTag == tag) {
  649. lastTag = tag;
  650. count++;
  651. continue;
  652. }
  653. encode(lastTag, count, compiledPattern);
  654. lastTag = tag;
  655. count = 1;
  656. }
  657. if (inQuote) {
  658. throw new IllegalArgumentException("Unterminated quote");
  659. }
  660. if (count != 0) {
  661. encode(lastTag, count, compiledPattern);
  662. }
  663. // Copy the compiled pattern to a char array
  664. int len = compiledPattern.length();
  665. char[] r = new char[len];
  666. compiledPattern.getChars(0, len, r, 0);
  667. return r;
  668. }
  669. /**
  670. * Encodes the given tag and length and puts encoded char(s) into buffer.
  671. */
  672. private static final void encode(int tag, int length, StringBuilder buffer) {
  673. if (length < 255) {
  674. buffer.append((char)(tag << 8 | length));
  675. } else {
  676. buffer.append((char)((tag << 8) | 0xff));
  677. buffer.append((char)(length >>> 16));
  678. buffer.append((char)(length & 0xffff));
  679. }
  680. }
  681. /* Initialize the fields we use to disambiguate ambiguous years. Separate
  682. * so we can call it from readObject().
  683. */
  684. private void initializeDefaultCentury() {
  685. calendar.setTime( new Date() );
  686. calendar.add( Calendar.YEAR, -80 );
  687. parseAmbiguousDatesAsAfter(calendar.getTime());
  688. }
  689. /* Define one-century window into which to disambiguate dates using
  690. * two-digit years.
  691. */
  692. private void parseAmbiguousDatesAsAfter(Date startDate) {
  693. defaultCenturyStart = startDate;
  694. calendar.setTime(startDate);
  695. defaultCenturyStartYear = calendar.get(Calendar.YEAR);
  696. }
  697. /**
  698. * Sets the 100-year period 2-digit years will be interpreted as being in
  699. * to begin on the date the user specifies.
  700. *
  701. * @param startDate During parsing, two digit years will be placed in the range
  702. * <code>startDate</code> to <code>startDate + 100 years</code>.
  703. * @see #get2DigitYearStart
  704. * @since 1.2
  705. */
  706. public void set2DigitYearStart(Date startDate) {
  707. parseAmbiguousDatesAsAfter(startDate);
  708. }
  709. /**
  710. * Returns the beginning date of the 100-year period 2-digit years are interpreted
  711. * as being within.
  712. *
  713. * @return the start of the 100-year period into which two digit years are
  714. * parsed
  715. * @see #set2DigitYearStart
  716. * @since 1.2
  717. */
  718. public Date get2DigitYearStart() {
  719. return defaultCenturyStart;
  720. }
  721. /**
  722. * Formats the given <code>Date</code> into a date/time string and appends
  723. * the result to the given <code>StringBuffer</code>.
  724. *
  725. * @param date the date-time value to be formatted into a date-time string.
  726. * @param toAppendTo where the new date-time text is to be appended.
  727. * @param pos the formatting position. On input: an alignment field,
  728. * if desired. On output: the offsets of the alignment field.
  729. * @return the formatted date-time string.
  730. * @exception NullPointerException if the given date is null
  731. */
  732. public StringBuffer format(Date date, StringBuffer toAppendTo,
  733. FieldPosition pos)
  734. {
  735. pos.beginIndex = pos.endIndex = 0;
  736. return format(date, toAppendTo, pos.getFieldDelegate());
  737. }
  738. // Called from Format after creating a FieldDelegate
  739. private StringBuffer format(Date date, StringBuffer toAppendTo,
  740. FieldDelegate delegate) {
  741. // Convert input date to time field list
  742. calendar.setTime(date);
  743. for (int i = 0; i < compiledPattern.length; ) {
  744. int tag = compiledPattern[i] >>> 8;
  745. int count = compiledPattern[i++] & 0xff;
  746. if (count == 255) {
  747. count = compiledPattern[i++] << 16;
  748. count |= compiledPattern[i++];
  749. }
  750. switch (tag) {
  751. case TAG_QUOTE_ASCII_CHAR:
  752. toAppendTo.append((char)count);
  753. break;
  754. case TAG_QUOTE_CHARS:
  755. toAppendTo.append(compiledPattern, i, count);
  756. i += count;
  757. break;
  758. default:
  759. subFormat(tag, count, delegate, toAppendTo);
  760. break;
  761. }
  762. }
  763. return toAppendTo;
  764. }
  765. /**
  766. * Formats an Object producing an <code>AttributedCharacterIterator</code>.
  767. * You can use the returned <code>AttributedCharacterIterator</code>
  768. * to build the resulting String, as well as to determine information
  769. * about the resulting String.
  770. * <p>
  771. * Each attribute key of the AttributedCharacterIterator will be of type
  772. * <code>DateFormat.Field</code>, with the corresponding attribute value
  773. * being the same as the attribute key.
  774. *
  775. * @exception NullPointerException if obj is null.
  776. * @exception IllegalArgumentException if the Format cannot format the
  777. * given object, or if the Format's pattern string is invalid.
  778. * @param obj The object to format
  779. * @return AttributedCharacterIterator describing the formatted value.
  780. * @since 1.4
  781. */
  782. public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
  783. StringBuffer sb = new StringBuffer();
  784. CharacterIteratorFieldDelegate delegate = new
  785. CharacterIteratorFieldDelegate();
  786. if (obj instanceof Date) {
  787. format((Date)obj, sb, delegate);
  788. }
  789. else if (obj instanceof Number) {
  790. format(new Date(((Number)obj).longValue()), sb, delegate);
  791. }
  792. else if (obj == null) {
  793. throw new NullPointerException(
  794. "formatToCharacterIterator must be passed non-null object");
  795. }
  796. else {
  797. throw new IllegalArgumentException(
  798. "Cannot format given Object as a Date");
  799. }
  800. return delegate.getIterator(sb.toString());
  801. }
  802. // Map index into pattern character string to Calendar field number
  803. private static final int[] PATTERN_INDEX_TO_CALENDAR_FIELD =
  804. {
  805. Calendar.ERA, Calendar.YEAR, Calendar.MONTH, Calendar.DATE,
  806. Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY, Calendar.MINUTE,
  807. Calendar.SECOND, Calendar.MILLISECOND, Calendar.DAY_OF_WEEK,
  808. Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK_IN_MONTH,
  809. Calendar.WEEK_OF_YEAR, Calendar.WEEK_OF_MONTH,
  810. Calendar.AM_PM, Calendar.HOUR, Calendar.HOUR, Calendar.ZONE_OFFSET,
  811. Calendar.ZONE_OFFSET
  812. };
  813. // Map index into pattern character string to DateFormat field number
  814. private static final int[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD = {
  815. DateFormat.ERA_FIELD, DateFormat.YEAR_FIELD, DateFormat.MONTH_FIELD,
  816. DateFormat.DATE_FIELD, DateFormat.HOUR_OF_DAY1_FIELD,
  817. DateFormat.HOUR_OF_DAY0_FIELD, DateFormat.MINUTE_FIELD,
  818. DateFormat.SECOND_FIELD, DateFormat.MILLISECOND_FIELD,
  819. DateFormat.DAY_OF_WEEK_FIELD, DateFormat.DAY_OF_YEAR_FIELD,
  820. DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD, DateFormat.WEEK_OF_YEAR_FIELD,
  821. DateFormat.WEEK_OF_MONTH_FIELD, DateFormat.AM_PM_FIELD,
  822. DateFormat.HOUR1_FIELD, DateFormat.HOUR0_FIELD,
  823. DateFormat.TIMEZONE_FIELD, DateFormat.TIMEZONE_FIELD,
  824. };
  825. // Maps from DecimalFormatSymbols index to Field constant
  826. private static final Field[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID = {
  827. Field.ERA, Field.YEAR, Field.MONTH, Field.DAY_OF_MONTH,
  828. Field.HOUR_OF_DAY1, Field.HOUR_OF_DAY0, Field.MINUTE,
  829. Field.SECOND, Field.MILLISECOND, Field.DAY_OF_WEEK,
  830. Field.DAY_OF_YEAR, Field.DAY_OF_WEEK_IN_MONTH,
  831. Field.WEEK_OF_YEAR, Field.WEEK_OF_MONTH,
  832. Field.AM_PM, Field.HOUR1, Field.HOUR0, Field.TIME_ZONE,
  833. Field.TIME_ZONE,
  834. };
  835. /**
  836. * Private member function that does the real date/time formatting.
  837. */
  838. private void subFormat(int patternCharIndex, int count,
  839. FieldDelegate delegate, StringBuffer buffer)
  840. {
  841. int maxIntCount = Integer.MAX_VALUE;
  842. String current = null;
  843. int beginOffset = buffer.length();
  844. int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
  845. int value = calendar.get(field);
  846. // Note: zeroPaddingNumber() assumes that maxDigits is either
  847. // 2 or maxIntCount. If we make any changes to this,
  848. // zeroPaddingNumber() must be fixed.
  849. switch (patternCharIndex) {
  850. case 0: // 'G' - ERA
  851. current = formatData.eras[value];
  852. break;
  853. case 1: // 'y' - YEAR
  854. if (count >= 4)
  855. zeroPaddingNumber(value, count, maxIntCount, buffer);
  856. else // count < 4
  857. zeroPaddingNumber(value, 2, 2, buffer); // clip 1996 to 96
  858. break;
  859. case 2: // 'M' - MONTH
  860. if (count >= 4)
  861. current = formatData.months[value];
  862. else if (count == 3)
  863. current = formatData.shortMonths[value];
  864. else
  865. zeroPaddingNumber(value+1, count, maxIntCount, buffer);
  866. break;
  867. case 4: // 'k' - HOUR_OF_DAY: 1-based. eg, 23:59 + 1 hour =>> 24:59
  868. if (value == 0)
  869. zeroPaddingNumber(calendar.getMaximum(Calendar.HOUR_OF_DAY)+1,
  870. count, maxIntCount, buffer);
  871. else
  872. zeroPaddingNumber(value, count, maxIntCount, buffer);
  873. break;
  874. case 9: // 'E' - DAY_OF_WEEK
  875. if (count >= 4)
  876. current = formatData.weekdays[value];
  877. else // count < 4, use abbreviated form if exists
  878. current = formatData.shortWeekdays[value];
  879. break;
  880. case 14: // 'a' - AM_PM
  881. current = formatData.ampms[value];
  882. break;
  883. case 15: // 'h' - HOUR:1-based. eg, 11PM + 1 hour =>> 12 AM
  884. if (value == 0)
  885. zeroPaddingNumber(calendar.getLeastMaximum(Calendar.HOUR)+1,
  886. count, maxIntCount, buffer);
  887. else
  888. zeroPaddingNumber(value, count, maxIntCount, buffer);
  889. break;
  890. case 17: // 'z' - ZONE_OFFSET
  891. int zoneIndex =
  892. formatData.getZoneIndex(calendar.getTimeZone().getID());
  893. if (zoneIndex == -1) {
  894. value = calendar.get(Calendar.ZONE_OFFSET) +
  895. calendar.get(Calendar.DST_OFFSET);
  896. buffer.append(ZoneInfoFile.toCustomID(value));
  897. } else {
  898. int index = (calendar.get(Calendar.DST_OFFSET) == 0) ? 1: 3;
  899. if (count < 4) {
  900. // Use the short name
  901. index++;
  902. }
  903. buffer.append(formatData.zoneStrings[zoneIndex][index]);
  904. }
  905. break;
  906. case 18: // 'Z' - ZONE_OFFSET ("-/+hhmm" form)
  907. value = (calendar.get(Calendar.ZONE_OFFSET) +
  908. calendar.get(Calendar.DST_OFFSET)) / 60000;
  909. int width = 4;
  910. if (value >= 0) {
  911. buffer.append('+');
  912. } else {
  913. width++;
  914. }
  915. int num = (value / 60) * 100 + (value % 60);
  916. CalendarUtils.sprintf0d(buffer, num, width);
  917. break;
  918. default:
  919. // case 3: // 'd' - DATE
  920. // case 5: // 'H' - HOUR_OF_DAY:0-based. eg, 23:59 + 1 hour =>> 00:59
  921. // case 6: // 'm' - MINUTE
  922. // case 7: // 's' - SECOND
  923. // case 8: // 'S' - MILLISECOND
  924. // case 10: // 'D' - DAY_OF_YEAR
  925. // case 11: // 'F' - DAY_OF_WEEK_IN_MONTH
  926. // case 12: // 'w' - WEEK_OF_YEAR
  927. // case 13: // 'W' - WEEK_OF_MONTH
  928. // case 16: // 'K' - HOUR: 0-based. eg, 11PM + 1 hour =>> 0 AM
  929. zeroPaddingNumber(value, count, maxIntCount, buffer);
  930. break;
  931. } // switch (patternCharIndex)
  932. if (current != null) {
  933. buffer.append(current);
  934. }
  935. int fieldID = PATTERN_INDEX_TO_DATE_FORMAT_FIELD[patternCharIndex];
  936. Field f = PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID[patternCharIndex];
  937. delegate.formatted(fieldID, f, f, beginOffset, buffer.length(), buffer);
  938. }
  939. /**
  940. * Formats a number with the specified minimum and maximum number of digits.
  941. */
  942. private final void zeroPaddingNumber(int value, int minDigits, int maxDigits, StringBuffer buffer)
  943. {
  944. // Optimization for 1, 2 and 4 digit numbers. This should
  945. // cover most cases of formatting date/time related items.
  946. // Note: This optimization code assumes that maxDigits is
  947. // either 2 or Integer.MAX_VALUE (maxIntCount in format()).
  948. try {
  949. if (zeroDigit == 0) {
  950. zeroDigit = ((DecimalFormat)numberFormat).getDecimalFormatSymbols().getZeroDigit();
  951. }
  952. if (value >= 0) {
  953. if (value < 100 && minDigits >= 1 && minDigits <= 2) {
  954. if (value < 10) {
  955. if (minDigits == 2) {
  956. buffer.append(zeroDigit);
  957. }
  958. buffer.append((char)(zeroDigit + value));
  959. } else {
  960. buffer.append((char)(zeroDigit + value / 10));
  961. buffer.append((char)(zeroDigit + value % 10));
  962. }
  963. return;
  964. } else if (value >= 1000 && value < 10000) {
  965. if (minDigits == 4) {
  966. buffer.append((char)(zeroDigit + value / 1000));
  967. value %= 1000;
  968. buffer.append((char)(zeroDigit + value / 100));
  969. value %= 100;
  970. buffer.append((char)(zeroDigit + value / 10));
  971. buffer.append((char)(zeroDigit + value % 10));
  972. return;
  973. }
  974. if (minDigits == 2 && maxDigits == 2) {
  975. zeroPaddingNumber(value % 100, 2, 2, buffer);
  976. return;
  977. }
  978. }
  979. }
  980. } catch (Exception e) {
  981. }
  982. numberFormat.setMinimumIntegerDigits(minDigits);
  983. numberFormat.setMaximumIntegerDigits(maxDigits);
  984. numberFormat.format((long)value, buffer, DontCareFieldPosition.INSTANCE);
  985. }
  986. /**
  987. * Parses text from a string to produce a <code>Date</code>.
  988. * <p>
  989. * The method attempts to parse text starting at the index given by
  990. * <code>pos</code>.
  991. * If parsing succeeds, then the index of <code>pos</code> is updated
  992. * to the index after the last character used (parsing does not necessarily
  993. * use all characters up to the end of the string), and the parsed
  994. * date is returned. The updated <code>pos</code> can be used to
  995. * indicate the starting point for the next call to this method.
  996. * If an error occurs, then the index of <code>pos</code> is not
  997. * changed, the error index of <code>pos</code> is set to the index of
  998. * the character where the error occurred, and null is returned.
  999. *
  1000. * @param text A <code>String</code>, part of which should be parsed.
  1001. * @param pos A <code>ParsePosition</code> object with index and error
  1002. * index information as described above.
  1003. * @return A <code>Date</code> parsed from the string. In case of
  1004. * error, returns null.
  1005. * @exception NullPointerException if <code>text</code> or <code>pos</code> is null.
  1006. */
  1007. public Date parse(String text, ParsePosition pos)
  1008. {
  1009. int start = pos.index;
  1010. int oldStart = start;
  1011. int textLength = text.length();
  1012. boolean[] ambiguousYear = {false};
  1013. calendar.clear(); // Clears all the time fields
  1014. for (int i = 0; i < compiledPattern.length; ) {
  1015. int tag = compiledPattern[i] >>> 8;
  1016. int count = compiledPattern[i++] & 0xff;
  1017. if (count == 255) {
  1018. count = compiledPattern[i++] << 16;
  1019. count |= compiledPattern[i++];
  1020. }
  1021. switch (tag) {
  1022. case TAG_QUOTE_ASCII_CHAR:
  1023. if (start >= textLength || text.charAt(start) != (char)count) {
  1024. pos.index = oldStart;
  1025. pos.errorIndex = start;
  1026. return null;
  1027. }
  1028. start++;
  1029. break;
  1030. case TAG_QUOTE_CHARS:
  1031. while (count-- > 0) {
  1032. if (start >= textLength || text.charAt(start) != compiledPattern[i++]) {
  1033. pos.index = oldStart;
  1034. pos.errorIndex = start;
  1035. return null;
  1036. }
  1037. start++;
  1038. }
  1039. break;
  1040. default:
  1041. // Peek the next pattern to determine if we need to
  1042. // obey the number of pattern letters for
  1043. // parsing. It's required when parsing contiguous
  1044. // digit text (e.g., "20010704") with a pattern which
  1045. // has no delimiters between fields, like "yyyyMMdd".
  1046. boolean obeyCount = false;
  1047. if (i < compiledPattern.length) {
  1048. int nextTag = compiledPattern[i] >>> 8;
  1049. if (!(nextTag == TAG_QUOTE_ASCII_CHAR || nextTag == TAG_QUOTE_CHARS)) {
  1050. obeyCount = true;
  1051. }
  1052. }
  1053. start = subParse(text, start, tag, count, obeyCount,
  1054. ambiguousYear, pos);
  1055. if (start < 0) {
  1056. pos.index = oldStart;
  1057. return null;
  1058. }
  1059. }
  1060. }
  1061. // At this point the fields of Calendar have been set. Calendar
  1062. // will fill in default values for missing fields when the time
  1063. // is computed.
  1064. pos.index = start;
  1065. // This part is a problem: When we call parsedDate.after, we compute the time.
  1066. // Take the date April 3 2004 at 2:30 am. When this is first set up, the year
  1067. // will be wrong if we're parsing a 2-digit year pattern. It will be 1904.
  1068. // April 3 1904 is a Sunday (unlike 2004) so it is the DST onset day. 2:30 am
  1069. // is therefore an "impossible" time, since the time goes from 1:59 to 3:00 am
  1070. // on that day. It is therefore parsed out to fields as 3:30 am. Then we
  1071. // add 100 years, and get April 3 2004 at 3:30 am. Note that April 3 2004 is
  1072. // a Saturday, so it can have a 2:30 am -- and it should. [LIU]
  1073. /*
  1074. Date parsedDate = calendar.getTime();
  1075. if( ambiguousYear[0] && !parsedDate.after(defaultCenturyStart) ) {
  1076. calendar.add(Calendar.YEAR, 100);
  1077. parsedDate = calendar.getTime();
  1078. }
  1079. */
  1080. // Because of the above condition, save off the fields in case we need to readjust.
  1081. // The procedure we use here is not particularly efficient, but there is no other
  1082. // way to do this given the API restrictions present in Calendar. We minimize
  1083. // inefficiency by only performing this computation when it might apply, that is,
  1084. // when the two-digit year is equal to the start year, and thus might fall at the
  1085. // front or the back of the default century. This only works because we adjust
  1086. // the year correctly to start with in other cases -- see subParse().
  1087. Date parsedDate;
  1088. try {
  1089. if (ambiguousYear[0]) // If this is true then the two-digit year == the default start year
  1090. {
  1091. // We need a copy of the fields, and we need to avoid triggering a call to
  1092. // complete(), which will recalculate the fields. Since we can't access
  1093. // the fields[] array in Calendar, we clone the entire object. This will
  1094. // stop working if Calendar.clone() is ever rewritten to call complete().
  1095. Calendar savedCalendar = (Calendar)calendar.clone();
  1096. parsedDate = calendar.getTime();
  1097. if (parsedDate.before(defaultCenturyStart))
  1098. {
  1099. // We can't use add here because that does a complete() first.
  1100. savedCalendar.set(Calendar.YEAR, defaultCenturyStartYear + 100);
  1101. parsedDate = savedCalendar.getTime();
  1102. }
  1103. }
  1104. else parsedDate = calendar.getTime();
  1105. }
  1106. // An IllegalArgumentException will be thrown by Calendar.getTime()
  1107. // if any fields are out of range, e.g., MONTH == 17.
  1108. catch (IllegalArgumentException e) {
  1109. pos.errorIndex = start;
  1110. pos.index = oldStart;
  1111. return null;
  1112. }
  1113. return parsedDate;
  1114. }
  1115. /**
  1116. * Private code-size reduction function used by subParse.
  1117. * @param text the time text being parsed.
  1118. * @param start where to start parsing.
  1119. * @param field the date field being parsed.
  1120. * @param data the string array to parsed.
  1121. * @return the new start position if matching succeeded; a negative number
  1122. * indicating matching failure, otherwise.
  1123. */
  1124. private int matchString(String text, int start, int field, String[] data)
  1125. {
  1126. int i = 0;
  1127. int count = data.length;
  1128. if (field == Calendar.DAY_OF_WEEK) i = 1;
  1129. // There may be multiple strings in the data[] array which begin with
  1130. // the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
  1131. // We keep track of the longest match, and return that. Note that this
  1132. // unfortunately requires us to test all array elements.
  1133. int bestMatchLength = 0, bestMatch = -1;
  1134. for (; i<count; ++i)
  1135. {
  1136. int length = data[i].length();
  1137. // Always compare if we have no match yet; otherwise only compare
  1138. // against potentially better matches (longer strings).
  1139. if (length > bestMatchLength &&
  1140. text.regionMatches(true, start, data[i], 0, length))
  1141. {
  1142. bestMatch = i;
  1143. bestMatchLength = length;
  1144. }
  1145. }
  1146. if (bestMatch >= 0)
  1147. {
  1148. calendar.set(field, bestMatch);
  1149. return start + bestMatchLength;
  1150. }
  1151. return -start;
  1152. }
  1153. private int matchZoneString(String text, int start, int zoneIndex) {
  1154. for (int j = 1; j <= 4; ++j) {
  1155. // Checking long and short zones [1 & 2],
  1156. // and long and short daylight [3 & 4].
  1157. String zoneName = formatData.zoneStrings[zoneIndex][j];
  1158. if (text.regionMatches(true, start,
  1159. zoneName, 0, zoneName.length())) {
  1160. return j;
  1161. }
  1162. }
  1163. return -1;
  1164. }
  1165. private boolean matchDSTString(String text, int start, int zoneIndex, int standardIndex) {
  1166. int index = standardIndex + 2;
  1167. String zoneName = formatData.zoneStrings[zoneIndex][index];
  1168. if (text.regionMatches(true, start,
  1169. zoneName, 0, zoneName.length())) {
  1170. return true;
  1171. }
  1172. return false;
  1173. }
  1174. /**
  1175. * find time zone 'text' matched zoneStrings and set to internal
  1176. * calendar.
  1177. */
  1178. private int subParseZoneString(String text, int start) {
  1179. boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
  1180. TimeZone currentTimeZone = getTimeZone();
  1181. // At this point, check for named time zones by looking through
  1182. // the locale data from the DateFormatZoneData strings.
  1183. // Want to be able to parse both short and long forms.
  1184. int zoneIndex =
  1185. formatData.getZoneIndex (currentTimeZone.getID());
  1186. TimeZone tz = null;
  1187. int j = 0, i = 0;
  1188. if ((zoneIndex != -1) && ((j = matchZoneString(text, start, zoneIndex)) > 0)) {
  1189. if (j <= 2) {
  1190. useSameName = matchDSTString(text, start, zoneIndex, j);
  1191. }
  1192. tz = TimeZone.getTimeZone(formatData.zoneStrings[zoneIndex][0]);
  1193. i = zoneIndex;
  1194. }
  1195. if (tz == null) {
  1196. zoneIndex =
  1197. formatData.getZoneIndex (TimeZone.getDefault().getID());
  1198. if ((zoneIndex != -1) && ((j = matchZoneString(text, start, zoneIndex)) > 0)) {
  1199. if (j <= 2) {
  1200. useSameName = matchDSTString(text, start, zoneIndex, j);
  1201. }
  1202. tz = TimeZone.getTimeZone(formatData.zoneStrings[zoneIndex][0]);
  1203. i = zoneIndex;
  1204. }
  1205. }
  1206. if (tz == null) {
  1207. for (i = 0; i < formatData.zoneStrings.length; i++) {
  1208. if ((j = matchZoneString(text, start, i)) > 0) {
  1209. if (j <= 2) {
  1210. useSameName = matchDSTString(text, start, i, j);
  1211. }
  1212. tz = TimeZone.getTimeZone(formatData.zoneStrings[i][0]);
  1213. break;
  1214. }
  1215. }
  1216. }
  1217. if (tz != null) { // Matched any ?
  1218. if (!tz.equals(currentTimeZone)) {
  1219. setTimeZone(tz);
  1220. }
  1221. // If the time zone matched uses the same name
  1222. // (abbreviation) for both standard and daylight time,
  1223. // let the time zone in the Calendar decide which one.
  1224. if (!useSameName) {
  1225. calendar.set(Calendar.ZONE_OFFSET, tz.getRawOffset());
  1226. calendar.set(Calendar.DST_OFFSET,
  1227. j >= 3 ? tz.getDSTSavings() : 0);
  1228. }
  1229. return (start + formatData.zoneStrings[i][j].length());
  1230. }
  1231. return 0;
  1232. }
  1233. /**
  1234. * Private member function that converts the parsed date strings into
  1235. * timeFields. Returns -start (for ParsePosition) if failed.
  1236. * @param text the time text to be parsed.
  1237. * @param start where to start parsing.
  1238. * @param ch the pattern character for the date field text to be parsed.
  1239. * @param count the count of a pattern character.
  1240. * @param obeyCount if true, then the next field directly abuts this one,
  1241. * and we should use the count to know when to stop parsing.
  1242. * @param ambiguousYear return parameter; upon return, if ambiguousYear[0]
  1243. * is true, then a two-digit year was parsed and may need to be readjusted.
  1244. * @param origPos origPos.errorIndex is used to return an error index
  1245. * at which a parse error occurred, if matching failure occurs.
  1246. * @return the new start position if matching succeeded; -1 indicating
  1247. * matching failure, otherwise. In case matching failure occurred,
  1248. * an error index is set to origPos.errorIndex.
  1249. */
  1250. private int subParse(String text, int start, int patternCharIndex, int count,
  1251. boolean obeyCount, boolean[] ambiguousYear,
  1252. ParsePosition origPos)
  1253. {
  1254. Number number = null;
  1255. int value = 0;
  1256. ParsePosition pos = new ParsePosition(0);
  1257. pos.index = start;
  1258. int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
  1259. // If there are any spaces here, skip over them. If we hit the end
  1260. // of the string, then fail.
  1261. for (;;) {
  1262. if (pos.index >= text.length()) {
  1263. origPos.errorIndex = start;
  1264. return -1;
  1265. }
  1266. char c = text.charAt(pos.index);
  1267. if (c != ' ' && c != '\t') break;
  1268. ++pos.index;
  1269. }
  1270. // We handle a few special cases here where we need to parse
  1271. // a number value. We handle further, more generic cases below. We need
  1272. // to handle some of them here because some fields require extra processing on
  1273. // the parsed value.
  1274. if (patternCharIndex == 4 /*HOUR_OF_DAY1_FIELD*/ ||
  1275. patternCharIndex == 15 /*HOUR1_FIELD*/ ||
  1276. (patternCharIndex == 2 /*MONTH_FIELD*/ && count <= 2) ||
  1277. patternCharIndex == 1)
  1278. {
  1279. // It would be good to unify this with the obeyCount logic below,
  1280. // but that's going to be difficult.
  1281. if (obeyCount)
  1282. {
  1283. if ((start+count) > text.length()) {
  1284. origPos.errorIndex = start;
  1285. return -1;
  1286. }
  1287. number = numberFormat.parse(text.substring(0, start+count), pos);
  1288. }
  1289. else number = numberFormat.parse(text, pos);
  1290. if (number == null) {
  1291. origPos.errorIndex = pos.index;
  1292. return -1;
  1293. }
  1294. value = number.intValue();
  1295. }
  1296. int index;
  1297. switch (patternCharIndex)
  1298. {
  1299. case 0: // 'G' - ERA
  1300. if ((index = matchString(text, start, Calendar.ERA, formatData.eras)) > 0) {
  1301. return index;
  1302. } else {
  1303. origPos.errorIndex = pos.index;
  1304. return -1;
  1305. }
  1306. case 1: // 'y' - YEAR
  1307. // If there are 3 or more YEAR pattern characters, this indicates
  1308. // that the year value is to be treated literally, without any
  1309. // two-digit year adjustments (e.g., from "01" to 2001). Otherwise
  1310. // we made adjustments to place the 2-digit year in the proper
  1311. // century, for parsed strings from "00" to "99". Any other string
  1312. // is treated literally: "2250", "-1", "1", "002".
  1313. if (count <= 2 && (pos.index - start) == 2
  1314. && Character.isDigit(text.charAt(start))
  1315. && Character.isDigit(text.charAt(start+1)))
  1316. {
  1317. // Assume for example that the defaultCenturyStart is 6/18/1903.
  1318. // This means that two-digit years will be forced into the range
  1319. // 6/18/1903 to 6/17/2003. As a result, years 00, 01, and 02
  1320. // correspond to 2000, 2001, and 2002. Years 04, 05, etc. correspond
  1321. // to 1904, 1905, etc. If the year is 03, then it is 2003 if the
  1322. // other fields specify a date before 6/18, or 1903 if they specify a
  1323. // date afterwards. As a result, 03 is an ambiguous year. All other
  1324. // two-digit years are unambiguous.
  1325. int ambiguousTwoDigitYear = defaultCenturyStartYear % 100;
  1326. ambiguousYear[0] = value == ambiguousTwoDigitYear;
  1327. value += (defaultCenturyStartYear100)*100 +
  1328. (value < ambiguousTwoDigitYear ? 100 : 0);
  1329. }
  1330. calendar.set(Calendar.YEAR, value);
  1331. return pos.index;
  1332. case 2: // 'M' - MONTH
  1333. if (count <= 2) // i.e., M or MM.
  1334. {
  1335. // Don't want to parse the month if it is a string
  1336. // while pattern uses numeric style: M or MM.
  1337. // [We computed 'value' above.]
  1338. calendar.set(Calendar.MONTH, value - 1);
  1339. return pos.index;
  1340. }
  1341. else
  1342. {
  1343. // count >= 3 // i.e., MMM or MMMM
  1344. // Want to be able to parse both short and long forms.
  1345. // Try count == 4 first:
  1346. int newStart = 0;
  1347. if ((newStart=matchString(text, start, Calendar.MONTH,
  1348. formatData.months)) > 0)
  1349. return newStart;
  1350. else // count == 4 failed, now try count == 3
  1351. if ((index = matchString(text, start, Calendar.MONTH,
  1352. formatData.shortMonths)) > 0) {
  1353. return index;
  1354. } else {
  1355. origPos.errorIndex = pos.index;
  1356. return -1;
  1357. }
  1358. }
  1359. case 4: // 'k' - HOUR_OF_DAY: 1-based. eg, 23:59 + 1 hour =>> 24:59
  1360. // [We computed 'value' above.]
  1361. if (value == calendar.getMaximum(Calendar.HOUR_OF_DAY)+1) value = 0;
  1362. calendar.set(Calendar.HOUR_OF_DAY, value);
  1363. return pos.index;
  1364. case 9: { // 'E' - DAY_OF_WEEK
  1365. // Want to be able to parse both short and long forms.
  1366. // Try count == 4 (DDDD) first:
  1367. int newStart = 0;
  1368. if ((newStart=matchString(text, start, Calendar.DAY_OF_WEEK,
  1369. formatData.weekdays)) > 0)
  1370. return newStart;
  1371. else // DDDD failed, now try DDD
  1372. if ((index = matchString(text, start, Calendar.DAY_OF_WEEK,
  1373. formatData.shortWeekdays)) > 0) {
  1374. return index;
  1375. } else {
  1376. origPos.errorIndex = pos.index;
  1377. return -1;
  1378. }
  1379. }
  1380. case 14: // 'a' - AM_PM
  1381. if ((index = matchString(text, start, Calendar.AM_PM, formatData.ampms)) > 0) {
  1382. return index;
  1383. } else {
  1384. origPos.errorIndex = pos.index;
  1385. return -1;
  1386. }
  1387. case 15: // 'h' - HOUR:1-based. eg, 11PM + 1 hour =>> 12 AM
  1388. // [We computed 'value' above.]
  1389. if (value == calendar.getLeastMaximum(Calendar.HOUR)+1) value = 0;
  1390. calendar.set(Calendar.HOUR, value);
  1391. return pos.index;
  1392. case 17: // 'z' - ZONE_OFFSET
  1393. case 18: // 'Z' - ZONE_OFFSET
  1394. // First try to parse generic forms such as GMT-07:00. Do this first
  1395. // in case localized DateFormatZoneData contains the string "GMT"
  1396. // for a zone; in that case, we don't want to match the first three
  1397. // characters of GMT+/-hh:mm etc.
  1398. {
  1399. int sign = 0;
  1400. int offset;
  1401. // For time zones that have no known names, look for strings
  1402. // of the form:
  1403. // GMT[+-]hours:minutes or
  1404. // GMT.
  1405. if ((text.length() - start) >= GMT.length() &&
  1406. text.regionMatches(true, start, GMT, 0, GMT.length())) {
  1407. int num;
  1408. calendar.set(Calendar.DST_OFFSET, 0);
  1409. pos.index = start + GMT.length();
  1410. try { // try-catch for "GMT" only time zone string
  1411. if( text.charAt(pos.index) == '+' ) {
  1412. sign = 1;
  1413. } else if( text.charAt(pos.index) == '-' ) {
  1414. sign = -1;
  1415. }
  1416. }
  1417. catch(StringIndexOutOfBoundsException e) {}
  1418. if (sign == 0) { /* "GMT" without offset */
  1419. calendar.set(Calendar.ZONE_OFFSET, 0 );
  1420. return pos.index;
  1421. }
  1422. // Look for hours.
  1423. try {
  1424. char c = text.charAt(++pos.index);
  1425. if (c < '0' || c > '9') { /* must be from '0' to '9'. */
  1426. origPos.errorIndex = pos.index;
  1427. return -1; // Wasn't actually a number.
  1428. } else {
  1429. num = c - '0';
  1430. }
  1431. if (text.charAt(++pos.index) != ':') {
  1432. c = text.charAt(pos.index);
  1433. if (c < '0' || c > '9') { /* must be from '0' to '9'. */
  1434. origPos.errorIndex = pos.index;
  1435. return -1; // Wasn't actually a number.
  1436. } else {
  1437. num *= 10;
  1438. num += c - '0';
  1439. pos.index++;
  1440. }
  1441. }
  1442. if (num > 23) {
  1443. origPos.errorIndex = pos.index - 1;
  1444. return -1; // Wasn't actually a number.
  1445. }
  1446. if (text.charAt(pos.index) != ':') {
  1447. origPos.errorIndex = pos.index;
  1448. return -1; // Wasn't actually a number.
  1449. }
  1450. }
  1451. catch(StringIndexOutOfBoundsException e) {
  1452. origPos.errorIndex = pos.index;
  1453. return -1; // Wasn't actually a number.
  1454. }
  1455. // Look for minutes.
  1456. offset = num * 60;
  1457. try {
  1458. char c = text.charAt(++pos.index);
  1459. if (c < '0' || c > '9') { /* must be from '0' to '9'. */
  1460. origPos.errorIndex = pos.index;
  1461. return -1; // Wasn't actually a number.
  1462. } else {
  1463. num = c - '0';
  1464. c = text.charAt(++pos.index);
  1465. if (c < '0' || c > '9') { /* must be from '0' to '9'. */
  1466. origPos.errorIndex = pos.index;
  1467. return -1; // Wasn't actually a number.
  1468. } else {
  1469. num *= 10;
  1470. num += c - '0';
  1471. }
  1472. }
  1473. if (num > 59) {
  1474. origPos.errorIndex = pos.index;
  1475. return -1; // Wasn't actually a number.
  1476. }
  1477. }
  1478. catch(StringIndexOutOfBoundsException e) {
  1479. origPos.errorIndex = pos.index;
  1480. return -1; // Wasn't actually a number.
  1481. }
  1482. offset += num;
  1483. // Fall through for final processing below of 'offset' and 'sign'.
  1484. }
  1485. else {
  1486. // At this point, check for named time zones by looking through
  1487. // the locale data from the DateFormatZoneData strings.
  1488. // Want to be able to parse both short and long forms.
  1489. int i = subParseZoneString(text, pos.index);
  1490. if (i != 0) {
  1491. return i;
  1492. }
  1493. // As a last resort, look for numeric timezones of the form
  1494. // [+-]hhmm as specified by RFC 822. This code is actually
  1495. // a little more permissive than RFC 822. It will try to do
  1496. // its best with numbers that aren't strictly 4 digits long.
  1497. try {
  1498. if( text.charAt(pos.index) == '+' ) {
  1499. sign = 1;
  1500. } else if( text.charAt(pos.index) == '-' ) {
  1501. sign = -1;
  1502. }
  1503. if (sign == 0) {
  1504. origPos.errorIndex = pos.index;
  1505. return -1;
  1506. }
  1507. // Look for hh.
  1508. int hours = 0;
  1509. char c = text.charAt(++pos.index);
  1510. if (c < '0' || c > '9') { /* must be from '0' to '9'. */
  1511. origPos.errorIndex = pos.index;
  1512. return -1; // Wasn't actually a number.
  1513. } else {
  1514. hours = c - '0';
  1515. c = text.charAt(++pos.index);
  1516. if (c < '0' || c > '9') { /* must be from '0' to '9'. */
  1517. origPos.errorIndex = pos.index;
  1518. return -1; // Wasn't actually a number.
  1519. } else {
  1520. hours *= 10;
  1521. hours += c - '0';
  1522. }
  1523. }
  1524. if (hours > 23) {
  1525. origPos.errorIndex = pos.index;
  1526. return -1; // Wasn't actually a number.
  1527. }
  1528. // Look for mm.
  1529. int minutes = 0;
  1530. c = text.charAt(++pos.index);
  1531. if (c < '0' || c > '9') { /* must be from '0' to '9'. */
  1532. origPos.errorIndex = pos.index;
  1533. return -1; // Wasn't actually a number.
  1534. } else {
  1535. minutes = c - '0';
  1536. c = text.charAt(++pos.index);
  1537. if (c < '0' || c > '9') { /* must be from '0' to '9'. */
  1538. origPos.errorIndex = pos.index;
  1539. return -1; // Wasn't actually a number.
  1540. } else {
  1541. minutes *= 10;
  1542. minutes += c - '0';
  1543. }
  1544. }
  1545. if (minutes > 59) {
  1546. origPos.errorIndex = pos.index;
  1547. return -1; // Wasn't actually a number.
  1548. }
  1549. offset = hours * 60 + minutes;
  1550. } catch(StringIndexOutOfBoundsException e) {
  1551. origPos.errorIndex = pos.index;
  1552. return -1; // Wasn't actually a number.
  1553. }
  1554. }
  1555. // Do the final processing for both of the above cases. We only
  1556. // arrive here if the form GMT+/-... or an RFC 822 form was seen.
  1557. if (sign != 0)
  1558. {
  1559. offset *= millisPerMinute * sign;
  1560. calendar.set(Calendar.ZONE_OFFSET, offset);
  1561. calendar.set(Calendar.DST_OFFSET, 0);
  1562. return ++pos.index;
  1563. }
  1564. }
  1565. // All efforts to parse a zone failed.
  1566. origPos.errorIndex = pos.index;
  1567. return -1;
  1568. default:
  1569. // case 3: // 'd' - DATE
  1570. // case 5: // 'H' - HOUR_OF_DAY:0-based. eg, 23:59 + 1 hour =>> 00:59
  1571. // case 6: // 'm' - MINUTE
  1572. // case 7: // 's' - SECOND
  1573. // case 8: // 'S' - MILLISECOND
  1574. // case 10: // 'D' - DAY_OF_YEAR
  1575. // case 11: // 'F' - DAY_OF_WEEK_IN_MONTH
  1576. // case 12: // 'w' - WEEK_OF_YEAR
  1577. // case 13: // 'W' - WEEK_OF_MONTH
  1578. // case 16: // 'K' - HOUR: 0-based. eg, 11PM + 1 hour =>> 0 AM
  1579. // Handle "generic" fields
  1580. if (obeyCount)
  1581. {
  1582. if ((start+count) > text.length()) {
  1583. origPos.errorIndex = pos.index;
  1584. return -1;
  1585. }
  1586. number = numberFormat.parse(text.substring(0, start+count), pos);
  1587. }
  1588. else number = numberFormat.parse(text, pos);
  1589. if (number != null) {
  1590. calendar.set(field, number.intValue());
  1591. return pos.index;
  1592. }
  1593. origPos.errorIndex = pos.index;
  1594. return -1;
  1595. }
  1596. }
  1597. /**
  1598. * Translates a pattern, mapping each character in the from string to the
  1599. * corresponding character in the to string.
  1600. *
  1601. * @exception IllegalArgumentException if the given pattern is invalid
  1602. */
  1603. private String translatePattern(String pattern, String from, String to) {
  1604. StringBuilder result = new StringBuilder();
  1605. boolean inQuote = false;
  1606. for (int i = 0; i < pattern.length(); ++i) {
  1607. char c = pattern.charAt(i);
  1608. if (inQuote) {
  1609. if (c == '\'')
  1610. inQuote = false;
  1611. }
  1612. else {
  1613. if (c == '\'')
  1614. inQuote = true;
  1615. else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
  1616. int ci = from.indexOf(c);
  1617. if (ci == -1)
  1618. throw new IllegalArgumentException("Illegal pattern " +
  1619. " character '" +
  1620. c + "'");
  1621. c = to.charAt(ci);
  1622. }
  1623. }
  1624. result.append(c);
  1625. }
  1626. if (inQuote)
  1627. throw new IllegalArgumentException("Unfinished quote in pattern");
  1628. return result.toString();
  1629. }
  1630. /**
  1631. * Returns a pattern string describing this date format.
  1632. *
  1633. * @return a pattern string describing this date format.
  1634. */
  1635. public String toPattern() {
  1636. return pattern;
  1637. }
  1638. /**
  1639. * Returns a localized pattern string describing this date format.
  1640. *
  1641. * @return a localized pattern string describing this date format.
  1642. */
  1643. public String toLocalizedPattern() {
  1644. return translatePattern(pattern,
  1645. formatData.patternChars,
  1646. formatData.localPatternChars);
  1647. }
  1648. /**
  1649. * Applies the given pattern string to this date format.
  1650. *
  1651. * @param pattern the new date and time pattern for this date format
  1652. * @exception NullPointerException if the given pattern is null
  1653. * @exception IllegalArgumentException if the given pattern is invalid
  1654. */
  1655. public void applyPattern (String pattern)
  1656. {
  1657. compiledPattern = compile(pattern);
  1658. this.pattern = pattern;
  1659. }
  1660. /**
  1661. * Applies the given localized pattern string to this date format.
  1662. *
  1663. * @param pattern a String to be mapped to the new date and time format
  1664. * pattern for this format
  1665. * @exception NullPointerException if the given pattern is null
  1666. * @exception IllegalArgumentException if the given pattern is invalid
  1667. */
  1668. public void applyLocalizedPattern(String pattern) {
  1669. String p = translatePattern(pattern,
  1670. formatData.localPatternChars,
  1671. formatData.patternChars);
  1672. compiledPattern = compile(p);
  1673. this.pattern = p;
  1674. }
  1675. /**
  1676. * Gets a copy of the date and time format symbols of this date format.
  1677. *
  1678. * @return the date and time format symbols of this date format
  1679. * @see #setDateFormatSymbols
  1680. */
  1681. public DateFormatSymbols getDateFormatSymbols()
  1682. {
  1683. return (DateFormatSymbols)formatData.clone();
  1684. }
  1685. /**
  1686. * Sets the date and time format symbols of this date format.
  1687. *
  1688. * @param newFormatSymbols the new date and time format symbols
  1689. * @exception NullPointerException if the given newFormatSymbols is null
  1690. * @see #getDateFormatSymbols
  1691. */
  1692. public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols)
  1693. {
  1694. this.formatData = (DateFormatSymbols)newFormatSymbols.clone();
  1695. }
  1696. /**
  1697. * Creates a copy of this <code>SimpleDateFormat</code>. This also
  1698. * clones the format's date format symbols.
  1699. *
  1700. * @return a clone of this <code>SimpleDateFormat</code>
  1701. */
  1702. public Object clone() {
  1703. SimpleDateFormat other = (SimpleDateFormat) super.clone();
  1704. other.formatData = (DateFormatSymbols) formatData.clone();
  1705. return other;
  1706. }
  1707. /**
  1708. * Returns the hash code value for this <code>SimpleDateFormat</code> object.
  1709. *
  1710. * @return the hash code value for this <code>SimpleDateFormat</code> object.
  1711. */
  1712. public int hashCode()
  1713. {
  1714. return pattern.hashCode();
  1715. // just enough fields for a reasonable distribution
  1716. }
  1717. /**
  1718. * Compares the given object with this <code>SimpleDateFormat</code> for
  1719. * equality.
  1720. *
  1721. * @return true if the given object is equal to this
  1722. * <code>SimpleDateFormat</code>
  1723. */
  1724. public boolean equals(Object obj)
  1725. {
  1726. if (!super.equals(obj)) return false; // super does class check
  1727. SimpleDateFormat that = (SimpleDateFormat) obj;
  1728. return (pattern.equals(that.pattern)
  1729. && formatData.equals(that.formatData));
  1730. }
  1731. /**
  1732. * After reading an object from the input stream, the format
  1733. * pattern in the object is verified.
  1734. * <p>
  1735. * @exception InvalidObjectException if the pattern is invalid
  1736. */
  1737. private void readObject(ObjectInputStream stream)
  1738. throws IOException, ClassNotFoundException {
  1739. stream.defaultReadObject();
  1740. try {
  1741. compiledPattern = compile(pattern);
  1742. } catch (Exception e) {
  1743. throw new InvalidObjectException("invalid pattern");
  1744. }
  1745. if (serialVersionOnStream < 1) {
  1746. // didn't have defaultCenturyStart field
  1747. initializeDefaultCentury();
  1748. }
  1749. else {
  1750. // fill in dependent transient field
  1751. parseAmbiguousDatesAsAfter(defaultCenturyStart);
  1752. }
  1753. serialVersionOnStream = currentSerialVersion;
  1754. // If the deserialized object has a SimpleTimeZone, try
  1755. // to replace it with a ZoneInfo equivalent in order to
  1756. // be compatible with the SimpleTimeZone-based
  1757. // implementation as much as possible.
  1758. TimeZone tz = getTimeZone();
  1759. if (tz instanceof SimpleTimeZone) {
  1760. String id = tz.getID();
  1761. TimeZone zi = TimeZone.getTimeZone(id);
  1762. if (zi != null && zi.hasSameRules(tz) && zi.getID().equals(id)) {
  1763. setTimeZone(zi);
  1764. }
  1765. }
  1766. }
  1767. }