1. /*
  2. * @(#)SimpleDateFormat.java 1.45 01/11/29
  3. *
  4. * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. /*
  8. * @(#)SimpleDateFormat.java 1.45 01/11/29
  9. *
  10. * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
  11. * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
  12. *
  13. * Portions copyright (c) 1996-1998 Sun Microsystems, Inc. All Rights Reserved.
  14. *
  15. * The original version of this source code and documentation is copyrighted
  16. * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  17. * materials are provided under terms of a License Agreement between Taligent
  18. * and Sun. This technology is protected by multiple US and International
  19. * patents. This notice and attribution to Taligent may not be removed.
  20. * Taligent is a registered trademark of Taligent, Inc.
  21. *
  22. * Permission to use, copy, modify, and distribute this software
  23. * and its documentation for NON-COMMERCIAL purposes and without
  24. * fee is hereby granted provided that this copyright notice
  25. * appears in all copies. Please refer to the file "copyright.html"
  26. * for further important copyright and licensing information.
  27. *
  28. * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  29. * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  30. * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  31. * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  32. * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  33. * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  34. *
  35. */
  36. package java.text;
  37. import java.util.TimeZone;
  38. import java.util.Calendar;
  39. import java.util.Date;
  40. import java.util.Locale;
  41. import java.util.ResourceBundle;
  42. import java.util.SimpleTimeZone;
  43. import java.util.GregorianCalendar;
  44. import java.io.ObjectInputStream;
  45. import java.io.IOException;
  46. import java.lang.ClassNotFoundException;
  47. import java.util.Hashtable;
  48. /**
  49. * <code>SimpleDateFormat</code> is a concrete class for formatting and
  50. * parsing dates in a locale-sensitive manner. It allows for formatting
  51. * (date -> text), parsing (text -> date), and normalization.
  52. *
  53. * <p>
  54. * <code>SimpleDateFormat</code> allows you to start by choosing
  55. * any user-defined patterns for date-time formatting. However, you
  56. * are encouraged to create a date-time formatter with either
  57. * <code>getTimeInstance</code>, <code>getDateInstance</code>, or
  58. * <code>getDateTimeInstance</code> in <code>DateFormat</code>. Each
  59. * of these class methods can return a date/time formatter initialized
  60. * with a default format pattern. You may modify the format pattern
  61. * using the <code>applyPattern</code> methods as desired.
  62. * For more information on using these methods, see
  63. * {@link DateFormat}.
  64. *
  65. * <p>
  66. * <strong>Time Format Syntax:</strong>
  67. * <p>
  68. * To specify the time format use a <em>time pattern</em> string.
  69. * In this pattern, all ASCII letters are reserved as pattern letters,
  70. * which are defined as the following:
  71. * <blockquote>
  72. * <pre>
  73. * Symbol Meaning Presentation Example
  74. * ------ ------- ------------ -------
  75. * G era designator (Text) AD
  76. * y year (Number) 1996
  77. * M month in year (Text & Number) July & 07
  78. * d day in month (Number) 10
  79. * h hour in am/pm (1~12) (Number) 12
  80. * H hour in day (0~23) (Number) 0
  81. * m minute in hour (Number) 30
  82. * s second in minute (Number) 55
  83. * S millisecond (Number) 978
  84. * E day in week (Text) Tuesday
  85. * D day in year (Number) 189
  86. * F day of week in month (Number) 2 (2nd Wed in July)
  87. * w week in year (Number) 27
  88. * W week in month (Number) 2
  89. * a am/pm marker (Text) PM
  90. * k hour in day (1~24) (Number) 24
  91. * K hour in am/pm (0~11) (Number) 0
  92. * z time zone (Text) Pacific Standard Time
  93. * ' escape for text (Delimiter)
  94. * '' single quote (Literal) '
  95. * </pre>
  96. * </blockquote>
  97. * The count of pattern letters determine the format.
  98. * <p>
  99. * <strong>(Text)</strong>: 4 or more pattern letters--use full form,
  100. * < 4--use short or abbreviated form if one exists.
  101. * <p>
  102. * <strong>(Number)</strong>: the minimum number of digits. Shorter
  103. * numbers are zero-padded to this amount. Year is handled specially;
  104. * that is, if the count of 'y' is 2, the Year will be truncated to 2 digits.
  105. * <p>
  106. * <strong>(Text & Number)</strong>: 3 or over, use text, otherwise use number.
  107. * <p>
  108. * Any characters in the pattern that are not in the ranges of ['a'..'z']
  109. * and ['A'..'Z'] will be treated as quoted text. For instance, characters
  110. * like ':', '.', ' ', '#' and '@' will appear in the resulting time text
  111. * even they are not embraced within single quotes.
  112. * <p>
  113. * A pattern containing any invalid pattern letter will result in a thrown
  114. * exception during formatting or parsing.
  115. *
  116. * <p>
  117. * <strong>Examples Using the US Locale:</strong>
  118. * <blockquote>
  119. * <pre>
  120. * Format Pattern Result
  121. * -------------- -------
  122. * "yyyy.MM.dd G 'at' hh:mm:ss z" ->> 1996.07.10 AD at 15:08:56 PDT
  123. * "EEE, MMM d, ''yy" ->> Wed, July 10, '96
  124. * "h:mm a" ->> 12:08 PM
  125. * "hh 'o''clock' a, zzzz" ->> 12 o'clock PM, Pacific Daylight Time
  126. * "K:mm a, z" ->> 0:00 PM, PST
  127. * "yyyyy.MMMMM.dd GGG hh:mm aaa" ->> 1996.July.10 AD 12:08 PM
  128. * </pre>
  129. * </blockquote>
  130. * <strong>Code Sample:</strong>
  131. * <blockquote>
  132. * <pre>
  133. * SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, "PST");
  134. * pdt.setStartRule(DateFields.APRIL, 1, DateFields.SUNDAY, 2*60*60*1000);
  135. * pdt.setEndRule(DateFields.OCTOBER, -1, DateFields.SUNDAY, 2*60*60*1000);
  136. * <br>
  137. * // Format the current time.
  138. * SimpleDateFormat formatter
  139. * = new SimpleDateFormat ("yyyy.MM.dd G 'at' hh:mm:ss a zzz");
  140. * Date currentTime_1 = new Date();
  141. * String dateString = formatter.format(currentTime_1);
  142. * <br>
  143. * // Parse the previous string back into a Date.
  144. * ParsePosition pos = new ParsePosition(0);
  145. * Date currentTime_2 = formatter.parse(dateString, pos);
  146. * </pre>
  147. * </blockquote>
  148. * In the example, the time value <code>currentTime_2</code> obtained from
  149. * parsing will be equal to <code>currentTime_1</code>. However, they may not be
  150. * equal if the am/pm marker 'a' is left out from the format pattern while
  151. * the "hour in am/pm" pattern symbol is used. This information loss can
  152. * happen when formatting the time in PM.
  153. *
  154. * <p>
  155. * When parsing a date string using the abbreviated year pattern ("y" or "yy"),
  156. * SimpleDateFormat must interpret the abbreviated year
  157. * relative to some century. It does this by adjusting dates to be
  158. * within 80 years before and 20 years after the time the SimpleDateFormat
  159. * instance is created. For example, using a pattern of "MM/dd/yy" and a
  160. * SimpleDateFormat instance created on Jan 1, 1997, the string
  161. * "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64"
  162. * would be interpreted as May 4, 1964.
  163. * During parsing, only strings consisting of exactly two digits, as defined by
  164. * {@link Character#isDigit(char)}, will be parsed into the default century.
  165. * Any other numeric string, such as a one digit string, a three or more digit
  166. * string, or a two digit string that isn't all digits (for example, "-1"), is
  167. * interpreted literally. So "01/02/3" or "01/02/003" are parsed, using the
  168. * same pattern, as Jan 2, 3 AD. Likewise, "01/02/-3" is parsed as Jan 2, 4 BC.
  169. *
  170. * <p>
  171. * If the year pattern has more than two 'y' characters, the year is
  172. * interpreted literally, regardless of the number of digits. So using the
  173. * pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.
  174. *
  175. * <p>
  176. * For time zones that have no names, use strings GMT+hours:minutes or
  177. * GMT-hours:minutes.
  178. *
  179. * <p>
  180. * The calendar defines what is the first day of the week, the first week
  181. * of the year, whether hours are zero based or not (0 vs 12 or 24), and the
  182. * time zone. There is one common decimal format to handle all the numbers;
  183. * the digit count is handled programmatically according to the pattern.
  184. *
  185. * @see java.util.Calendar
  186. * @see java.util.GregorianCalendar
  187. * @see java.util.TimeZone
  188. * @see DateFormat
  189. * @see DateFormatSymbols
  190. * @see DecimalFormat
  191. * @version 1.29 01/15/98
  192. * @author Mark Davis, Chen-Lieh Huang, Alan Liu
  193. */
  194. public class SimpleDateFormat extends DateFormat {
  195. // the official serial version ID which says cryptically
  196. // which version we're compatible with
  197. static final long serialVersionUID = 4774881970558875024L;
  198. // the internal serial version which says which version was written
  199. // - 0 (default) for version up to JDK 1.1.3
  200. // - 1 for version from JDK 1.1.4, which includes a new field
  201. static final int currentSerialVersion = 1;
  202. /**
  203. * The version of the serialized data on the stream. Possible values:
  204. * <ul>
  205. * <li><b>0</b> or not present on stream: JDK 1.1.3. This version
  206. * has no <code>defaultCenturyStart</code> on stream.
  207. * <li><b>1</b> JDK 1.1.4 or later. This version adds
  208. * <code>defaultCenturyStart</code>.
  209. * </ul>
  210. * When streaming out this class, the most recent format
  211. * and the highest allowable <code>serialVersionOnStream</code>
  212. * is written.
  213. * @serial
  214. * @since JDK1.1.4
  215. */
  216. private int serialVersionOnStream = currentSerialVersion;
  217. /**
  218. * The pattern string of this formatter. This is always a non-localized
  219. * pattern. May not be null. See class documentation for details.
  220. * @serial
  221. */
  222. private String pattern;
  223. /**
  224. * The symbols used by this formatter for week names, month names,
  225. * etc. May not be null.
  226. * @serial
  227. * @see java.text.DateFormatSymbols
  228. */
  229. private DateFormatSymbols formatData;
  230. /**
  231. * We map dates with two-digit years into the century starting at
  232. * <code>defaultCenturyStart</code>, which may be any date. May
  233. * not be null.
  234. * @serial
  235. * @since JDK1.1.4
  236. */
  237. private Date defaultCenturyStart;
  238. transient private int defaultCenturyStartYear;
  239. private static final int millisPerHour = 60 * 60 * 1000;
  240. private static final int millisPerMinute = 60 * 1000;
  241. // For time zones that have no names, use strings GMT+minutes and
  242. // GMT-minutes. For instance, in France the time zone is GMT+60.
  243. private static final String GMT_PLUS = "GMT+";
  244. private static final String GMT_MINUS = "GMT-";
  245. private static final String GMT = "GMT";
  246. /**
  247. * Cache to hold the DateTimePatterns of a Locale.
  248. */
  249. private static Hashtable cachedLocaleData = new Hashtable(3);
  250. /**
  251. * Construct a SimpleDateFormat using the default pattern for the default
  252. * locale. <b>Note:</b> Not all locales support SimpleDateFormat; for full
  253. * generality, use the factory methods in the DateFormat class.
  254. *
  255. * @see java.text.DateFormat
  256. */
  257. public SimpleDateFormat() {
  258. this(SHORT, SHORT + 4, Locale.getDefault());
  259. }
  260. /**
  261. * Construct a SimpleDateFormat using the given pattern in the default
  262. * locale. <b>Note:</b> Not all locales support SimpleDateFormat; for full
  263. * generality, use the factory methods in the DateFormat class.
  264. */
  265. public SimpleDateFormat(String pattern)
  266. {
  267. this(pattern, Locale.getDefault());
  268. }
  269. /**
  270. * Construct a SimpleDateFormat using the given pattern and locale.
  271. * <b>Note:</b> Not all locales support SimpleDateFormat; for full
  272. * generality, use the factory methods in the DateFormat class.
  273. */
  274. public SimpleDateFormat(String pattern, Locale loc)
  275. {
  276. this.pattern = pattern;
  277. this.formatData = new DateFormatSymbols(loc);
  278. initialize(loc);
  279. }
  280. /**
  281. * Construct a SimpleDateFormat using the given pattern and
  282. * locale-specific symbol data.
  283. */
  284. public SimpleDateFormat(String pattern, DateFormatSymbols formatData)
  285. {
  286. this.pattern = pattern;
  287. this.formatData = (DateFormatSymbols) formatData.clone();
  288. initialize(Locale.getDefault());
  289. }
  290. /* Package-private, called by DateFormat factory methods */
  291. SimpleDateFormat(int timeStyle, int dateStyle, Locale loc) {
  292. /* try the cache first */
  293. String[] dateTimePatterns = (String[]) cachedLocaleData.get(loc);
  294. if (dateTimePatterns == null) { /* cache miss */
  295. ResourceBundle r = ResourceBundle.getBundle
  296. ("java.text.resources.LocaleElements", loc);
  297. dateTimePatterns = r.getStringArray("DateTimePatterns");
  298. /* update cache */
  299. cachedLocaleData.put(loc, dateTimePatterns);
  300. }
  301. formatData = new DateFormatSymbols(loc);
  302. if ((timeStyle >= 0) && (dateStyle >= 0)) {
  303. Object[] dateTimeArgs = {dateTimePatterns[timeStyle],
  304. dateTimePatterns[dateStyle]};
  305. pattern = MessageFormat.format(dateTimePatterns[8], dateTimeArgs);
  306. }
  307. else if (timeStyle >= 0)
  308. pattern = dateTimePatterns[timeStyle];
  309. else if (dateStyle >= 0)
  310. pattern = dateTimePatterns[dateStyle];
  311. else
  312. throw new IllegalArgumentException("No date or time style specified");
  313. initialize(loc);
  314. }
  315. /* Initialize calendar and numberFormat fields */
  316. private void initialize(Locale loc) {
  317. // The format object must be constructed using the symbols for this zone.
  318. // However, the calendar should use the current default TimeZone.
  319. // If this is not contained in the locale zone strings, then the zone
  320. // will be formatted using generic GMT+/-H:MM nomenclature.
  321. calendar = Calendar.getInstance(TimeZone.getDefault(), loc);
  322. numberFormat = NumberFormat.getInstance(loc);
  323. numberFormat.setGroupingUsed(false);
  324. if (numberFormat instanceof DecimalFormat)
  325. ((DecimalFormat)numberFormat).setDecimalSeparatorAlwaysShown(false);
  326. numberFormat.setParseIntegerOnly(true); /* So that dd.MM.yy can be parsed */
  327. numberFormat.setMinimumFractionDigits(0); // To prevent "Jan 1.00, 1997.00"
  328. initializeDefaultCentury();
  329. }
  330. /* Initialize the fields we use to disambiguate ambiguous years. Separate
  331. * so we can call it from readObject().
  332. */
  333. private void initializeDefaultCentury() {
  334. calendar.setTime( new Date() );
  335. calendar.add( Calendar.YEAR, -80 );
  336. parseAmbiguousDatesAsAfter(calendar.getTime());
  337. }
  338. /* Define one-century window into which to disambiguate dates using
  339. * two-digit years.
  340. */
  341. private void parseAmbiguousDatesAsAfter(Date startDate) {
  342. defaultCenturyStart = startDate;
  343. calendar.setTime(startDate);
  344. defaultCenturyStartYear = calendar.get(Calendar.YEAR);
  345. }
  346. /**
  347. * Sets the 100-year period 2-digit years will be interpreted as being in
  348. * to begin on the date the user specifies.
  349. * @param startDate During parsing, two digit years will be placed in the range
  350. * <code>startDate</code> to <code>startDate + 100 years</code>.
  351. */
  352. public void set2DigitYearStart(Date startDate) {
  353. parseAmbiguousDatesAsAfter(startDate);
  354. }
  355. /**
  356. * Returns the beginning date of the 100-year period 2-digit years are interpreted
  357. * as being within.
  358. * @return the start of the 100-year period into which two digit years are
  359. * parsed
  360. */
  361. public Date get2DigitYearStart() {
  362. return defaultCenturyStart;
  363. }
  364. /**
  365. * Overrides DateFormat
  366. * <p>Formats a date or time, which is the standard millis
  367. * since January 1, 1970, 00:00:00 GMT.
  368. * <p>Example: using the US locale:
  369. * "yyyy.MM.dd G 'at' HH:mm:ss zzz" ->> 1996.07.10 AD at 15:08:56 PDT
  370. * @param date the date-time value to be formatted into a date-time string.
  371. * @param toAppendTo where the new date-time text is to be appended.
  372. * @param pos the formatting position. On input: an alignment field,
  373. * if desired. On output: the offsets of the alignment field.
  374. * @return the formatted date-time string.
  375. * @see java.text.DateFormat
  376. */
  377. public StringBuffer format(Date date, StringBuffer toAppendTo,
  378. FieldPosition pos)
  379. {
  380. // Initialize
  381. pos.beginIndex = pos.endIndex = 0;
  382. // Convert input date to time field list
  383. calendar.setTime(date);
  384. boolean inQuote = false; // true when between single quotes
  385. char prevCh = 0; // previous pattern character
  386. int count = 0; // number of time prevCh repeated
  387. for (int i=0; i<pattern.length(); ++i) {
  388. char ch = pattern.charAt(i);
  389. // Use subFormat() to format a repeated pattern character
  390. // when a different pattern or non-pattern character is seen
  391. if (ch != prevCh && count > 0) {
  392. toAppendTo.append(
  393. subFormat(prevCh, count, toAppendTo.length(), pos));
  394. count = 0;
  395. }
  396. if (ch == '\'') {
  397. // Consecutive single quotes are a single quote literal,
  398. // either outside of quotes or between quotes
  399. if ((i+1)<pattern.length() && pattern.charAt(i+1) == '\'') {
  400. toAppendTo.append('\'');
  401. ++i;
  402. } else {
  403. inQuote = !inQuote;
  404. }
  405. } else if (!inQuote
  406. && (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z')) {
  407. // ch is a date-time pattern character to be interpreted
  408. // by subFormat(); count the number of times it is repeated
  409. prevCh = ch;
  410. ++count;
  411. }
  412. else {
  413. // Append quoted characters and unquoted non-pattern characters
  414. toAppendTo.append(ch);
  415. }
  416. }
  417. // Format the last item in the pattern, if any
  418. if (count > 0) {
  419. toAppendTo.append(
  420. subFormat(prevCh, count, toAppendTo.length(), pos));
  421. }
  422. return toAppendTo;
  423. }
  424. // Map index into pattern character string to Calendar field number
  425. private static final int[] PATTERN_INDEX_TO_CALENDAR_FIELD =
  426. {
  427. Calendar.ERA, Calendar.YEAR, Calendar.MONTH, Calendar.DATE,
  428. Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY, Calendar.MINUTE,
  429. Calendar.SECOND, Calendar.MILLISECOND, Calendar.DAY_OF_WEEK,
  430. Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK_IN_MONTH,
  431. Calendar.WEEK_OF_YEAR, Calendar.WEEK_OF_MONTH,
  432. Calendar.AM_PM, Calendar.HOUR, Calendar.HOUR, Calendar.ZONE_OFFSET
  433. };
  434. // Map index into pattern character string to DateFormat field number
  435. private static final int[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD = {
  436. DateFormat.ERA_FIELD, DateFormat.YEAR_FIELD, DateFormat.MONTH_FIELD,
  437. DateFormat.DATE_FIELD, DateFormat.HOUR_OF_DAY1_FIELD,
  438. DateFormat.HOUR_OF_DAY0_FIELD, DateFormat.MINUTE_FIELD,
  439. DateFormat.SECOND_FIELD, DateFormat.MILLISECOND_FIELD,
  440. DateFormat.DAY_OF_WEEK_FIELD, DateFormat.DAY_OF_YEAR_FIELD,
  441. DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD, DateFormat.WEEK_OF_YEAR_FIELD,
  442. DateFormat.WEEK_OF_MONTH_FIELD, DateFormat.AM_PM_FIELD,
  443. DateFormat.HOUR1_FIELD, DateFormat.HOUR0_FIELD,
  444. DateFormat.TIMEZONE_FIELD,
  445. };
  446. // Private member function that does the real date/time formatting.
  447. private String subFormat(char ch, int count, int beginOffset,
  448. FieldPosition pos)
  449. throws IllegalArgumentException
  450. {
  451. int patternCharIndex = -1;
  452. int maxIntCount = 10;
  453. String current = "";
  454. if ((patternCharIndex=formatData.patternChars.indexOf(ch)) == -1)
  455. throw new IllegalArgumentException("Illegal pattern character " +
  456. "'" + ch + "'");
  457. int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
  458. int value = calendar.get(field);
  459. switch (patternCharIndex) {
  460. case 0: // 'G' - ERA
  461. current = formatData.eras[value];
  462. break;
  463. case 1: // 'y' - YEAR
  464. if (count >= 4)
  465. // current = zeroPaddingNumber(value, 4, count);
  466. current = zeroPaddingNumber(value, 4, maxIntCount);
  467. else // count < 4
  468. current = zeroPaddingNumber(value, 2, 2); // clip 1996 to 96
  469. break;
  470. case 2: // 'M' - MONTH
  471. if (count >= 4)
  472. current = formatData.months[value];
  473. else if (count == 3)
  474. current = formatData.shortMonths[value];
  475. else
  476. current = zeroPaddingNumber(value+1, count, maxIntCount);
  477. break;
  478. case 4: // 'k' - HOUR_OF_DAY: 1-based. eg, 23:59 + 1 hour =>> 24:59
  479. if (value == 0)
  480. current = zeroPaddingNumber(
  481. calendar.getMaximum(Calendar.HOUR_OF_DAY)+1,
  482. count, maxIntCount);
  483. else
  484. current = zeroPaddingNumber(value, count, maxIntCount);
  485. break;
  486. case 8: // 'S' - MILLISECOND
  487. if (count > 3)
  488. count = 3;
  489. else if (count == 2)
  490. value = value / 10;
  491. else if (count == 1)
  492. value = value / 100;
  493. current = zeroPaddingNumber(value, count, maxIntCount);
  494. break;
  495. case 9: // 'E' - DAY_OF_WEEK
  496. if (count >= 4)
  497. current = formatData.weekdays[value];
  498. else // count < 4, use abbreviated form if exists
  499. current = formatData.shortWeekdays[value];
  500. break;
  501. case 14: // 'a' - AM_PM
  502. current = formatData.ampms[value];
  503. break;
  504. case 15: // 'h' - HOUR:1-based. eg, 11PM + 1 hour =>> 12 AM
  505. if (value == 0)
  506. current = zeroPaddingNumber(
  507. calendar.getLeastMaximum(Calendar.HOUR)+1,
  508. count, maxIntCount);
  509. else
  510. current = zeroPaddingNumber(value, count, maxIntCount);
  511. break;
  512. case 17: // 'z' - ZONE_OFFSET
  513. int zoneIndex
  514. = formatData.getZoneIndex (calendar.getTimeZone().getID());
  515. if (zoneIndex == -1)
  516. {
  517. // For time zones that have no names, use strings
  518. // GMT+hours:minutes and GMT-hours:minutes.
  519. // For instance, France time zone uses GMT+01:00.
  520. StringBuffer zoneString = new StringBuffer();
  521. value = calendar.get(Calendar.ZONE_OFFSET) +
  522. calendar.get(Calendar.DST_OFFSET);
  523. if (value < 0)
  524. {
  525. zoneString.append(GMT_MINUS);
  526. value = -value; // suppress the '-' sign for text display.
  527. }
  528. else
  529. zoneString.append(GMT_PLUS);
  530. zoneString.append(
  531. zeroPaddingNumber((int)(valuemillisPerHour), 2, 2));
  532. zoneString.append(':');
  533. zoneString.append(
  534. zeroPaddingNumber(
  535. (int)((value%millisPerHour)/millisPerMinute), 2, 2));
  536. current = zoneString.toString();
  537. }
  538. else if (calendar.get(Calendar.DST_OFFSET) != 0)
  539. {
  540. if (count >= 4)
  541. current = formatData.zoneStrings[zoneIndex][3];
  542. else
  543. // count < 4, use abbreviated form if exists
  544. current = formatData.zoneStrings[zoneIndex][4];
  545. }
  546. else
  547. {
  548. if (count >= 4)
  549. current = formatData.zoneStrings[zoneIndex][1];
  550. else
  551. current = formatData.zoneStrings[zoneIndex][2];
  552. }
  553. break;
  554. default:
  555. // case 3: // 'd' - DATE
  556. // case 5: // 'H' - HOUR_OF_DAY:0-based. eg, 23:59 + 1 hour =>> 00:59
  557. // case 6: // 'm' - MINUTE
  558. // case 7: // 's' - SECOND
  559. // case 10: // 'D' - DAY_OF_YEAR
  560. // case 11: // 'F' - DAY_OF_WEEK_IN_MONTH
  561. // case 12: // 'w' - WEEK_OF_YEAR
  562. // case 13: // 'W' - WEEK_OF_MONTH
  563. // case 16: // 'K' - HOUR: 0-based. eg, 11PM + 1 hour =>> 0 AM
  564. current = zeroPaddingNumber(value, count, maxIntCount);
  565. break;
  566. } // switch (patternCharIndex)
  567. if (pos.field == PATTERN_INDEX_TO_DATE_FORMAT_FIELD[patternCharIndex]) {
  568. // set for the first occurence only.
  569. if (pos.beginIndex == 0 && pos.endIndex == 0) {
  570. pos.beginIndex = beginOffset;
  571. pos.endIndex = beginOffset + current.length();
  572. }
  573. }
  574. return current;
  575. }
  576. // Pad the shorter numbers up to maxCount digits.
  577. private String zeroPaddingNumber(long value, int minDigits, int maxDigits)
  578. {
  579. numberFormat.setMinimumIntegerDigits(minDigits);
  580. numberFormat.setMaximumIntegerDigits(maxDigits);
  581. return numberFormat.format(value);
  582. }
  583. /**
  584. * Overrides DateFormat
  585. * @see java.text.DateFormat
  586. */
  587. public Date parse(String text, ParsePosition pos)
  588. {
  589. int start = pos.index;
  590. int oldStart = start;
  591. boolean[] ambiguousYear = {false};
  592. calendar.clear(); // Clears all the time fields
  593. boolean inQuote = false; // inQuote set true when hits 1st single quote
  594. char prevCh = 0;
  595. int count = 0;
  596. int interQuoteCount = 1; // Number of chars between quotes
  597. for (int i=0; i<pattern.length(); ++i)
  598. {
  599. char ch = pattern.charAt(i);
  600. if (inQuote)
  601. {
  602. if (ch == '\'')
  603. {
  604. // ends with 2nd single quote
  605. inQuote = false;
  606. // two consecutive quotes outside a quote means we have
  607. // a quote literal we need to match.
  608. if (count == 0)
  609. {
  610. if (start >= text.length() || ch != text.charAt(start))
  611. {
  612. pos.index = oldStart;
  613. pos.errorIndex = start;
  614. return null;
  615. }
  616. ++start;
  617. }
  618. count = 0;
  619. interQuoteCount = 0;
  620. }
  621. else
  622. {
  623. // pattern uses text following from 1st single quote.
  624. if (start >= text.length() || ch != text.charAt(start)) {
  625. // Check for cases like: 'at' in pattern vs "xt"
  626. // in time text, where 'a' doesn't match with 'x'.
  627. // If fail to match, return null.
  628. pos.index = oldStart; // left unchanged
  629. pos.errorIndex = start;
  630. return null;
  631. }
  632. ++count;
  633. ++start;
  634. }
  635. }
  636. else // !inQuote
  637. {
  638. if (ch == '\'')
  639. {
  640. inQuote = true;
  641. if (count > 0) // handle cases like: e'at'
  642. {
  643. int startOffset = start;
  644. start=subParse(text, start, prevCh, count,
  645. false, ambiguousYear);
  646. if ( start<0 ) {
  647. pos.errorIndex = startOffset;
  648. pos.index = oldStart;
  649. return null;
  650. }
  651. count = 0;
  652. }
  653. if (interQuoteCount == 0)
  654. {
  655. // This indicates two consecutive quotes inside a quote,
  656. // for example, 'o''clock'. We need to parse this as
  657. // representing a single quote within the quote.
  658. int startOffset = start;
  659. if (start >= text.length() || ch != text.charAt(start))
  660. {
  661. pos.errorIndex = startOffset;
  662. pos.index = oldStart;
  663. return null;
  664. }
  665. ++start;
  666. count = 1; // Make it look like we never left
  667. }
  668. }
  669. else if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z')
  670. {
  671. // ch is a date-time pattern
  672. if (ch != prevCh && count > 0) // e.g., yyyyMMdd
  673. {
  674. int startOffset = start;
  675. // This is the only case where we pass in 'true' for
  676. // obeyCount. That's because the next field directly
  677. // abuts this one, so we have to use the count to know when
  678. // to stop parsing. [LIU]
  679. start = subParse(text, start, prevCh, count, true,
  680. ambiguousYear);
  681. if (start < 0) {
  682. pos.errorIndex = startOffset;
  683. pos.index = oldStart;
  684. return null;
  685. }
  686. prevCh = ch;
  687. count = 1;
  688. }
  689. else
  690. {
  691. if (ch != prevCh)
  692. prevCh = ch;
  693. count++;
  694. }
  695. }
  696. else if (count > 0)
  697. {
  698. // handle cases like: MM-dd-yy, HH:mm:ss, or yyyy MM dd,
  699. // where ch = '-', ':', or ' ', repectively.
  700. int startOffset = start;
  701. start=subParse(text, start, prevCh, count,
  702. false, ambiguousYear);
  703. if ( start < 0 ) {
  704. pos.errorIndex = startOffset;
  705. pos.index = oldStart;
  706. return null;
  707. }
  708. if (start >= text.length() || ch != text.charAt(start)) {
  709. // handle cases like: 'MMMM dd' in pattern vs. "janx20"
  710. // in time text, where ' ' doesn't match with 'x'.
  711. pos.errorIndex = start;
  712. pos.index = oldStart;
  713. return null;
  714. }
  715. start++;
  716. count = 0;
  717. prevCh = 0;
  718. }
  719. else // any other unquoted characters
  720. {
  721. if (start >= text.length() || ch != text.charAt(start)) {
  722. // handle cases like: 'MMMM dd' in pattern vs.
  723. // "jan,,,20" in time text, where " " doesn't
  724. // match with ",,,".
  725. pos.errorIndex = start;
  726. pos.index = oldStart;
  727. return null;
  728. }
  729. start++;
  730. }
  731. ++interQuoteCount;
  732. }
  733. }
  734. // Parse the last item in the pattern
  735. if (count > 0)
  736. {
  737. int startOffset = start;
  738. start=subParse(text, start, prevCh, count,
  739. false, ambiguousYear);
  740. if ( start < 0 ) {
  741. pos.index = oldStart;
  742. pos.errorIndex = startOffset;
  743. return null;
  744. }
  745. }
  746. // At this point the fields of Calendar have been set. Calendar
  747. // will fill in default values for missing fields when the time
  748. // is computed.
  749. pos.index = start;
  750. // This part is a problem: When we call parsedDate.after, we compute the time.
  751. // Take the date April 3 2004 at 2:30 am. When this is first set up, the year
  752. // will be wrong if we're parsing a 2-digit year pattern. It will be 1904.
  753. // April 3 1904 is a Sunday (unlike 2004) so it is the DST onset day. 2:30 am
  754. // is therefore an "impossible" time, since the time goes from 1:59 to 3:00 am
  755. // on that day. It is therefore parsed out to fields as 3:30 am. Then we
  756. // add 100 years, and get April 3 2004 at 3:30 am. Note that April 3 2004 is
  757. // a Saturday, so it can have a 2:30 am -- and it should. [LIU]
  758. /*
  759. Date parsedDate = calendar.getTime();
  760. if( ambiguousYear[0] && !parsedDate.after(defaultCenturyStart) ) {
  761. calendar.add(Calendar.YEAR, 100);
  762. parsedDate = calendar.getTime();
  763. }
  764. */
  765. // Because of the above condition, save off the fields in case we need to readjust.
  766. // The procedure we use here is not particularly efficient, but there is no other
  767. // way to do this given the API restrictions present in Calendar. We minimize
  768. // inefficiency by only performing this computation when it might apply, that is,
  769. // when the two-digit year is equal to the start year, and thus might fall at the
  770. // front or the back of the default century. This only works because we adjust
  771. // the year correctly to start with in other cases -- see subParse().
  772. Date parsedDate;
  773. try {
  774. if (ambiguousYear[0]) // If this is true then the two-digit year == the default start year
  775. {
  776. // We need a copy of the fields, and we need to avoid triggering a call to
  777. // complete(), which will recalculate the fields. Since we can't access
  778. // the fields[] array in Calendar, we clone the entire object. This will
  779. // stop working if Calendar.clone() is ever rewritten to call complete().
  780. Calendar savedCalendar = (Calendar)calendar.clone();
  781. parsedDate = calendar.getTime();
  782. if (parsedDate.before(defaultCenturyStart))
  783. {
  784. // We can't use add here because that does a complete() first.
  785. savedCalendar.set(Calendar.YEAR, defaultCenturyStartYear + 100);
  786. parsedDate = savedCalendar.getTime();
  787. }
  788. }
  789. else parsedDate = calendar.getTime();
  790. }
  791. // An IllegalArgumentException will be thrown by Calendar.getTime()
  792. // if any fields are out of range, e.g., MONTH == 17.
  793. catch (IllegalArgumentException e) {
  794. pos.errorIndex = start;
  795. pos.index = oldStart;
  796. return null;
  797. }
  798. return parsedDate;
  799. }
  800. /**
  801. * Private code-size reduction function used by subParse.
  802. * @param text the time text being parsed.
  803. * @param start where to start parsing.
  804. * @param field the date field being parsed.
  805. * @param data the string array to parsed.
  806. * @return the new start position if matching succeeded; a negative number
  807. * indicating matching failure, otherwise.
  808. */
  809. private int matchString(String text, int start, int field, String[] data)
  810. {
  811. int i = 0;
  812. int count = data.length;
  813. if (field == Calendar.DAY_OF_WEEK) i = 1;
  814. // There may be multiple strings in the data[] array which begin with
  815. // the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
  816. // We keep track of the longest match, and return that. Note that this
  817. // unfortunately requires us to test all array elements.
  818. int bestMatchLength = 0, bestMatch = -1;
  819. for (; i<count; ++i)
  820. {
  821. int length = data[i].length();
  822. // Always compare if we have no match yet; otherwise only compare
  823. // against potentially better matches (longer strings).
  824. if (length > bestMatchLength &&
  825. text.regionMatches(true, start, data[i], 0, length))
  826. {
  827. bestMatch = i;
  828. bestMatchLength = length;
  829. }
  830. }
  831. if (bestMatch >= 0)
  832. {
  833. calendar.set(field, bestMatch);
  834. return start + bestMatchLength;
  835. }
  836. return -start;
  837. }
  838. /**
  839. * Private member function that converts the parsed date strings into
  840. * timeFields. Returns -start (for ParsePosition) if failed.
  841. * @param text the time text to be parsed.
  842. * @param start where to start parsing.
  843. * @param ch the pattern character for the date field text to be parsed.
  844. * @param count the count of a pattern character.
  845. * @param obeyCount if true, then the next field directly abuts this one,
  846. * and we should use the count to know when to stop parsing.
  847. * @param ambiguousYear return parameter; upon return, if ambiguousYear[0]
  848. * is true, then a two-digit year was parsed and may need to be readjusted.
  849. * @return the new start position if matching succeeded; a negative number
  850. * indicating matching failure, otherwise.
  851. */
  852. private int subParse(String text, int start, char ch, int count,
  853. boolean obeyCount, boolean[] ambiguousYear)
  854. {
  855. Number number;
  856. int value = 0;
  857. int i;
  858. ParsePosition pos = new ParsePosition(0);
  859. int patternCharIndex = -1;
  860. if ((patternCharIndex=formatData.patternChars.indexOf(ch)) == -1)
  861. return -start;
  862. pos.index = start;
  863. int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
  864. // If there are any spaces here, skip over them. If we hit the end
  865. // of the string, then fail.
  866. for (;;) {
  867. if (pos.index >= text.length()) return -start;
  868. char c = text.charAt(pos.index);
  869. if (c != ' ' && c != '\t') break;
  870. ++pos.index;
  871. }
  872. // We handle a few special cases here where we need to parse
  873. // a number value. We handle further, more generic cases below. We need
  874. // to handle some of them here because some fields require extra processing on
  875. // the parsed value.
  876. if (patternCharIndex == 4 /*HOUR_OF_DAY1_FIELD*/ ||
  877. patternCharIndex == 15 /*HOUR1_FIELD*/ ||
  878. (patternCharIndex == 2 /*MONTH_FIELD*/ && count <= 2) ||
  879. patternCharIndex == 1 /*YEAR*/)
  880. {
  881. int parseStart = pos.getIndex(); // WORK AROUND BUG IN NUMBER FORMAT IN 1.2B3
  882. // It would be good to unify this with the obeyCount logic below,
  883. // but that's going to be difficult.
  884. if (obeyCount)
  885. {
  886. if ((start+count) > text.length()) return -start;
  887. number = numberFormat.parse(text.substring(0, start+count), pos);
  888. }
  889. else number = numberFormat.parse(text, pos);
  890. if (number == null
  891. // WORK AROUND BUG IN NUMBER FORMAT IN 1.2B3
  892. || pos.getIndex() == parseStart)
  893. return -start;
  894. value = number.intValue();
  895. }
  896. switch (patternCharIndex)
  897. {
  898. case 0: // 'G' - ERA
  899. return matchString(text, start, Calendar.ERA, formatData.eras);
  900. case 1: // 'y' - YEAR
  901. // If there are 3 or more YEAR pattern characters, this indicates
  902. // that the year value is to be treated literally, without any
  903. // two-digit year adjustments (e.g., from "01" to 2001). Otherwise
  904. // we made adjustments to place the 2-digit year in the proper
  905. // century, for parsed strings from "00" to "99". Any other string
  906. // is treated literally: "2250", "-1", "1", "002".
  907. if (count <= 2 && (pos.index - start) == 2
  908. && Character.isDigit(text.charAt(start))
  909. && Character.isDigit(text.charAt(start+1)))
  910. {
  911. // Assume for example that the defaultCenturyStart is 6/18/1903.
  912. // This means that two-digit years will be forced into the range
  913. // 6/18/1903 to 6/17/2003. As a result, years 00, 01, and 02
  914. // correspond to 2000, 2001, and 2002. Years 04, 05, etc. correspond
  915. // to 1904, 1905, etc. If the year is 03, then it is 2003 if the
  916. // other fields specify a date before 6/18, or 1903 if they specify a
  917. // date afterwards. As a result, 03 is an ambiguous year. All other
  918. // two-digit years are unambiguous.
  919. int ambiguousTwoDigitYear = defaultCenturyStartYear % 100;
  920. ambiguousYear[0] = value == ambiguousTwoDigitYear;
  921. value += (defaultCenturyStartYear100)*100 +
  922. (value < ambiguousTwoDigitYear ? 100 : 0);
  923. }
  924. calendar.set(Calendar.YEAR, value);
  925. return pos.index;
  926. case 2: // 'M' - MONTH
  927. if (count <= 2) // i.e., M or MM.
  928. {
  929. // Don't want to parse the month if it is a string
  930. // while pattern uses numeric style: M or MM.
  931. // [We computed 'value' above.]
  932. calendar.set(Calendar.MONTH, value - 1);
  933. return pos.index;
  934. }
  935. else
  936. {
  937. // count >= 3 // i.e., MMM or MMMM
  938. // Want to be able to parse both short and long forms.
  939. // Try count == 4 first:
  940. int newStart = 0;
  941. if ((newStart=matchString(text, start, Calendar.MONTH,
  942. formatData.months)) > 0)
  943. return newStart;
  944. else // count == 4 failed, now try count == 3
  945. return matchString(text, start, Calendar.MONTH,
  946. formatData.shortMonths);
  947. }
  948. case 4: // 'k' - HOUR_OF_DAY: 1-based. eg, 23:59 + 1 hour =>> 24:59
  949. // [We computed 'value' above.]
  950. if (value == calendar.getMaximum(Calendar.HOUR_OF_DAY)+1) value = 0;
  951. calendar.set(Calendar.HOUR_OF_DAY, value);
  952. return pos.index;
  953. case 9: { // 'E' - DAY_OF_WEEK
  954. // Want to be able to parse both short and long forms.
  955. // Try count == 4 (DDDD) first:
  956. int newStart = 0;
  957. if ((newStart=matchString(text, start, Calendar.DAY_OF_WEEK,
  958. formatData.weekdays)) > 0)
  959. return newStart;
  960. else // DDDD failed, now try DDD
  961. return matchString(text, start, Calendar.DAY_OF_WEEK,
  962. formatData.shortWeekdays);
  963. }
  964. case 14: // 'a' - AM_PM
  965. return matchString(text, start, Calendar.AM_PM, formatData.ampms);
  966. case 15: // 'h' - HOUR:1-based. eg, 11PM + 1 hour =>> 12 AM
  967. // [We computed 'value' above.]
  968. if (value == calendar.getLeastMaximum(Calendar.HOUR)+1) value = 0;
  969. calendar.set(Calendar.HOUR, value);
  970. return pos.index;
  971. case 17: // 'z' - ZONE_OFFSET
  972. // First try to parse generic forms such as GMT-07:00. Do this first
  973. // in case localized DateFormatZoneData contains the string "GMT"
  974. // for a zone; in that case, we don't want to match the first three
  975. // characters of GMT+/-HH:MM etc.
  976. {
  977. int sign = 0;
  978. int offset;
  979. // For time zones that have no known names, look for strings
  980. // of the form:
  981. // GMT[+-]hours:minutes or
  982. // GMT[+-]hhmm or
  983. // GMT.
  984. if ((text.length() - start) > GMT.length() &&
  985. text.regionMatches(true, start, GMT, 0, GMT.length()))
  986. {
  987. calendar.set(Calendar.DST_OFFSET, 0);
  988. pos.index = start + GMT.length();
  989. if( text.charAt(pos.index) == '+' )
  990. sign = 1;
  991. else if( text.charAt(pos.index) == '-' )
  992. sign = -1;
  993. else {
  994. calendar.set(Calendar.ZONE_OFFSET, 0 );
  995. return pos.index;
  996. }
  997. // Look for hours:minutes or hhmm.
  998. pos.index++;
  999. // WORK AROUND BUG IN NUMBER FORMAT IN 1.2B3
  1000. int parseStart = pos.getIndex();
  1001. Number tzNumber = numberFormat.parse(text, pos);
  1002. if( tzNumber == null
  1003. // WORK AROUND BUG IN NUMBER FORMAT IN 1.2B3
  1004. || pos.getIndex() == parseStart) {
  1005. return -start;
  1006. }
  1007. if( text.charAt(pos.index) == ':' ) {
  1008. // This is the hours:minutes case
  1009. offset = tzNumber.intValue() * 60;
  1010. pos.index++;
  1011. // WORK AROUND BUG IN NUMBER FORMAT IN 1.2B3
  1012. parseStart = pos.getIndex();
  1013. tzNumber = numberFormat.parse(text, pos);
  1014. if( tzNumber == null
  1015. // WORK AROUND BUG IN NUMBER FORMAT IN 1.2B3
  1016. || pos.getIndex() == parseStart) {
  1017. return -start;
  1018. }
  1019. offset += tzNumber.intValue();
  1020. }
  1021. else {
  1022. // This is the hhmm case.
  1023. offset = tzNumber.intValue();
  1024. if( offset < 24 )
  1025. offset *= 60;
  1026. else
  1027. offset = offset % 100 + offset / 100 * 60;
  1028. }
  1029. // Fall through for final processing below of 'offset' and 'sign'.
  1030. }
  1031. else {
  1032. // At this point, check for named time zones by looking through
  1033. // the locale data from the DateFormatZoneData strings.
  1034. // Want to be able to parse both short and long forms.
  1035. for (i=0; i<formatData.zoneStrings.length; i++)
  1036. {
  1037. // Checking long and short zones [1 & 2],
  1038. // and long and short daylight [3 & 4].
  1039. int j = 1;
  1040. for (; j <= 4; ++j)
  1041. {
  1042. if (text.regionMatches(true, start,
  1043. formatData.zoneStrings[i][j], 0,
  1044. formatData.zoneStrings[i][j].length()))
  1045. break;
  1046. }
  1047. if (j <= 4)
  1048. {
  1049. TimeZone tz = TimeZone.getTimeZone(formatData.zoneStrings[i][0]);
  1050. calendar.set(Calendar.ZONE_OFFSET, tz.getRawOffset());
  1051. // Must call set() with something -- TODO -- Fix this to
  1052. // use the correct DST SAVINGS for the zone.
  1053. calendar.set(Calendar.DST_OFFSET, j >= 3 ? millisPerHour : 0);
  1054. return (start + formatData.zoneStrings[i][j].length());
  1055. }
  1056. }
  1057. // As a last resort, look for numeric timezones of the form
  1058. // [+-]hhmm as specified by RFC 822. This code is actually
  1059. // a little more permissive than RFC 822. It will try to do
  1060. // its best with numbers that aren't strictly 4 digits long.
  1061. DecimalFormat fmt = new DecimalFormat("+####;-####");
  1062. fmt.setParseIntegerOnly(true);
  1063. // WORK AROUND BUG IN NUMBER FORMAT IN 1.2B3
  1064. int parseStart = pos.getIndex();
  1065. Number tzNumber = fmt.parse( text, pos );
  1066. if( tzNumber == null
  1067. // WORK AROUND BUG IN NUMBER FORMAT IN 1.2B3
  1068. || pos.getIndex() == parseStart) {
  1069. return -start; // Wasn't actually a number.
  1070. }
  1071. offset = tzNumber.intValue();
  1072. sign = 1;
  1073. if( offset < 0 ) {
  1074. sign = -1;
  1075. offset = -offset;
  1076. }
  1077. if( offset < 24 )
  1078. offset = offset * 60;
  1079. else
  1080. offset = offset % 100 + offset / 100 * 60;
  1081. // Fall through for final processing below of 'offset' and 'sign'.
  1082. }
  1083. // Do the final processing for both of the above cases. We only
  1084. // arrive here if the form GMT+/-... or an RFC 822 form was seen.
  1085. if (sign != 0)
  1086. {
  1087. offset *= millisPerMinute * sign;
  1088. if (calendar.getTimeZone().useDaylightTime())
  1089. {
  1090. calendar.set(Calendar.DST_OFFSET, millisPerHour);
  1091. offset -= millisPerHour;
  1092. }
  1093. calendar.set(Calendar.ZONE_OFFSET, offset);
  1094. return pos.index;
  1095. }
  1096. }
  1097. // All efforts to parse a zone failed.
  1098. return -start;
  1099. default:
  1100. // case 3: // 'd' - DATE
  1101. // case 5: // 'H' - HOUR_OF_DAY:0-based. eg, 23:59 + 1 hour =>> 00:59
  1102. // case 6: // 'm' - MINUTE
  1103. // case 7: // 's' - SECOND
  1104. // case 8: // 'S' - MILLISECOND
  1105. // case 10: // 'D' - DAY_OF_YEAR
  1106. // case 11: // 'F' - DAY_OF_WEEK_IN_MONTH
  1107. // case 12: // 'w' - WEEK_OF_YEAR
  1108. // case 13: // 'W' - WEEK_OF_MONTH
  1109. // case 16: // 'K' - HOUR: 0-based. eg, 11PM + 1 hour =>> 0 AM
  1110. // WORK AROUND BUG IN NUMBER FORMAT IN 1.2B3
  1111. int parseStart = pos.getIndex();
  1112. // Handle "generic" fields
  1113. if (obeyCount)
  1114. {
  1115. if ((start+count) > text.length()) return -start;
  1116. number = numberFormat.parse(text.substring(0, start+count), pos);
  1117. }
  1118. else number = numberFormat.parse(text, pos);
  1119. if (number != null
  1120. // WORK AROUND BUG IN NUMBER FORMAT IN 1.2B3
  1121. && pos.getIndex() != parseStart) {
  1122. calendar.set(field, number.intValue());
  1123. return pos.index;
  1124. }
  1125. return -start;
  1126. }
  1127. }
  1128. /**
  1129. * Translate a pattern, mapping each character in the from string to the
  1130. * corresponding character in the to string.
  1131. */
  1132. private String translatePattern(String pattern, String from, String to) {
  1133. StringBuffer result = new StringBuffer();
  1134. boolean inQuote = false;
  1135. for (int i = 0; i < pattern.length(); ++i) {
  1136. char c = pattern.charAt(i);
  1137. if (inQuote) {
  1138. if (c == '\'')
  1139. inQuote = false;
  1140. }
  1141. else {
  1142. if (c == '\'')
  1143. inQuote = true;
  1144. else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
  1145. int ci = from.indexOf(c);
  1146. if (ci == -1)
  1147. throw new IllegalArgumentException("Illegal pattern " +
  1148. " character '" +
  1149. c + "'");
  1150. c = to.charAt(ci);
  1151. }
  1152. }
  1153. result.append(c);
  1154. }
  1155. if (inQuote)
  1156. throw new IllegalArgumentException("Unfinished quote in pattern");
  1157. return result.toString();
  1158. }
  1159. /**
  1160. * Return a pattern string describing this date format.
  1161. */
  1162. public String toPattern() {
  1163. return pattern;
  1164. }
  1165. /**
  1166. * Return a localized pattern string describing this date format.
  1167. */
  1168. public String toLocalizedPattern() {
  1169. return translatePattern(pattern,
  1170. formatData.patternChars,
  1171. formatData.localPatternChars);
  1172. }
  1173. /**
  1174. * Apply the given unlocalized pattern string to this date format.
  1175. */
  1176. public void applyPattern (String pattern)
  1177. {
  1178. this.pattern = pattern;
  1179. }
  1180. /**
  1181. * Apply the given localized pattern string to this date format.
  1182. */
  1183. public void applyLocalizedPattern(String pattern) {
  1184. this.pattern = translatePattern(pattern,
  1185. formatData.localPatternChars,
  1186. formatData.patternChars);
  1187. }
  1188. /**
  1189. * Gets the date/time formatting data.
  1190. * @return a copy of the date-time formatting data associated
  1191. * with this date-time formatter.
  1192. */
  1193. public DateFormatSymbols getDateFormatSymbols()
  1194. {
  1195. return (DateFormatSymbols)formatData.clone();
  1196. }
  1197. /**
  1198. * Allows you to set the date/time formatting data.
  1199. * @param newFormatData the given date-time formatting data.
  1200. */
  1201. public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols)
  1202. {
  1203. this.formatData = (DateFormatSymbols)newFormatSymbols.clone();
  1204. }
  1205. /**
  1206. * Overrides Cloneable
  1207. */
  1208. public Object clone() {
  1209. SimpleDateFormat other = (SimpleDateFormat) super.clone();
  1210. other.formatData = (DateFormatSymbols) formatData.clone();
  1211. return other;
  1212. }
  1213. /**
  1214. * Override hashCode.
  1215. * Generates the hash code for the SimpleDateFormat object
  1216. */
  1217. public int hashCode()
  1218. {
  1219. return pattern.hashCode();
  1220. // just enough fields for a reasonable distribution
  1221. }
  1222. /**
  1223. * Override equals.
  1224. */
  1225. public boolean equals(Object obj)
  1226. {
  1227. if (!super.equals(obj)) return false; // super does class check
  1228. SimpleDateFormat that = (SimpleDateFormat) obj;
  1229. return (pattern.equals(that.pattern)
  1230. && formatData.equals(that.formatData));
  1231. }
  1232. /**
  1233. * Override readObject.
  1234. */
  1235. private void readObject(ObjectInputStream stream)
  1236. throws IOException, ClassNotFoundException {
  1237. stream.defaultReadObject();
  1238. if (serialVersionOnStream < 1) {
  1239. // didn't have defaultCenturyStart field
  1240. initializeDefaultCentury();
  1241. }
  1242. else {
  1243. // fill in dependent transient field
  1244. parseAmbiguousDatesAsAfter(defaultCenturyStart);
  1245. }
  1246. serialVersionOnStream = currentSerialVersion;
  1247. }
  1248. }