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