1. /*
  2. * @(#)DateFormat.java 1.47 03/01/23
  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 - 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.io.InvalidObjectException;
  21. import java.util.HashMap;
  22. import java.util.Locale;
  23. import java.util.Map;
  24. import java.util.ResourceBundle;
  25. import java.util.MissingResourceException;
  26. import java.util.TimeZone;
  27. import java.util.Calendar;
  28. import java.util.GregorianCalendar;
  29. import java.util.Date;
  30. import sun.text.resources.LocaleData;
  31. /**
  32. * DateFormat is an abstract class for date/time formatting subclasses which
  33. * formats and parses dates or time in a language-independent manner.
  34. * The date/time formatting subclass, such as SimpleDateFormat, allows for
  35. * formatting (i.e., date -> text), parsing (text -> date), and
  36. * normalization. The date is represented as a <code>Date</code> object or
  37. * as the milliseconds since January 1, 1970, 00:00:00 GMT.
  38. *
  39. * <p>DateFormat provides many class methods for obtaining default date/time
  40. * formatters based on the default or a given locale and a number of formatting
  41. * styles. The formatting styles include FULL, LONG, MEDIUM, and SHORT. More
  42. * detail and examples of using these styles are provided in the method
  43. * descriptions.
  44. *
  45. * <p>DateFormat helps you to format and parse dates for any locale.
  46. * Your code can be completely independent of the locale conventions for
  47. * months, days of the week, or even the calendar format: lunar vs. solar.
  48. *
  49. * <p>To format a date for the current Locale, use one of the
  50. * static factory methods:
  51. * <pre>
  52. * myString = DateFormat.getDateInstance().format(myDate);
  53. * </pre>
  54. * <p>If you are formatting multiple dates, it is
  55. * more efficient to get the format and use it multiple times so that
  56. * the system doesn't have to fetch the information about the local
  57. * language and country conventions multiple times.
  58. * <pre>
  59. * DateFormat df = DateFormat.getDateInstance();
  60. * for (int i = 0; i < a.length; ++i) {
  61. * output.println(df.format(myDate[i]) + "; ");
  62. * }
  63. * </pre>
  64. * <p>To format a date for a different Locale, specify it in the
  65. * call to getDateInstance().
  66. * <pre>
  67. * DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
  68. * </pre>
  69. * <p>You can use a DateFormat to parse also.
  70. * <pre>
  71. * myDate = df.parse(myString);
  72. * </pre>
  73. * <p>Use getDateInstance to get the normal date format for that country.
  74. * There are other static factory methods available.
  75. * Use getTimeInstance to get the time format for that country.
  76. * Use getDateTimeInstance to get a date and time format. You can pass in
  77. * different options to these factory methods to control the length of the
  78. * result; from SHORT to MEDIUM to LONG to FULL. The exact result depends
  79. * on the locale, but generally:
  80. * <ul><li>SHORT is completely numeric, such as 12.13.52 or 3:30pm
  81. * <li>MEDIUM is longer, such as Jan 12, 1952
  82. * <li>LONG is longer, such as January 12, 1952 or 3:30:32pm
  83. * <li>FULL is pretty completely specified, such as
  84. * Tuesday, April 12, 1952 AD or 3:30:42pm PST.
  85. * </ul>
  86. *
  87. * <p>You can also set the time zone on the format if you wish.
  88. * If you want even more control over the format or parsing,
  89. * (or want to give your users more control),
  90. * you can try casting the DateFormat you get from the factory methods
  91. * to a SimpleDateFormat. This will work for the majority
  92. * of countries; just remember to put it in a try block in case you
  93. * encounter an unusual one.
  94. *
  95. * <p>You can also use forms of the parse and format methods with
  96. * ParsePosition and FieldPosition to
  97. * allow you to
  98. * <ul><li>progressively parse through pieces of a string.
  99. * <li>align any particular field, or find out where it is for selection
  100. * on the screen.
  101. * </ul>
  102. *
  103. * <h4><a name="synchronization">Synchronization</a></h4>
  104. *
  105. * <p>
  106. * Date formats are not synchronized.
  107. * It is recommended to create separate format instances for each thread.
  108. * If multiple threads access a format concurrently, it must be synchronized
  109. * externally.
  110. *
  111. * @see Format
  112. * @see NumberFormat
  113. * @see SimpleDateFormat
  114. * @see java.util.Calendar
  115. * @see java.util.GregorianCalendar
  116. * @see java.util.TimeZone
  117. * @version 1.47 01/23/03
  118. * @author Mark Davis, Chen-Lieh Huang, Alan Liu
  119. */
  120. public abstract class DateFormat extends Format {
  121. /**
  122. * The calendar that <code>DateFormat</code> uses to produce the time field
  123. * values needed to implement date and time formatting. Subclasses should
  124. * initialize this to a calendar appropriate for the locale associated with
  125. * this <code>DateFormat</code>.
  126. * @serial
  127. */
  128. protected Calendar calendar;
  129. /**
  130. * The number formatter that <code>DateFormat</code> uses to format numbers
  131. * in dates and times. Subclasses should initialize this to a number format
  132. * appropriate for the locale associated with this <code>DateFormat</code>.
  133. * @serial
  134. */
  135. protected NumberFormat numberFormat;
  136. /**
  137. * Useful constant for ERA field alignment.
  138. * Used in FieldPosition of date/time formatting.
  139. */
  140. public final static int ERA_FIELD = 0;
  141. /**
  142. * Useful constant for YEAR field alignment.
  143. * Used in FieldPosition of date/time formatting.
  144. */
  145. public final static int YEAR_FIELD = 1;
  146. /**
  147. * Useful constant for MONTH field alignment.
  148. * Used in FieldPosition of date/time formatting.
  149. */
  150. public final static int MONTH_FIELD = 2;
  151. /**
  152. * Useful constant for DATE field alignment.
  153. * Used in FieldPosition of date/time formatting.
  154. */
  155. public final static int DATE_FIELD = 3;
  156. /**
  157. * Useful constant for one-based HOUR_OF_DAY field alignment.
  158. * Used in FieldPosition of date/time formatting.
  159. * HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock.
  160. * For example, 23:59 + 01:00 results in 24:59.
  161. */
  162. public final static int HOUR_OF_DAY1_FIELD = 4;
  163. /**
  164. * Useful constant for zero-based HOUR_OF_DAY field alignment.
  165. * Used in FieldPosition of date/time formatting.
  166. * HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock.
  167. * For example, 23:59 + 01:00 results in 00:59.
  168. */
  169. public final static int HOUR_OF_DAY0_FIELD = 5;
  170. /**
  171. * Useful constant for MINUTE field alignment.
  172. * Used in FieldPosition of date/time formatting.
  173. */
  174. public final static int MINUTE_FIELD = 6;
  175. /**
  176. * Useful constant for SECOND field alignment.
  177. * Used in FieldPosition of date/time formatting.
  178. */
  179. public final static int SECOND_FIELD = 7;
  180. /**
  181. * Useful constant for MILLISECOND field alignment.
  182. * Used in FieldPosition of date/time formatting.
  183. */
  184. public final static int MILLISECOND_FIELD = 8;
  185. /**
  186. * Useful constant for DAY_OF_WEEK field alignment.
  187. * Used in FieldPosition of date/time formatting.
  188. */
  189. public final static int DAY_OF_WEEK_FIELD = 9;
  190. /**
  191. * Useful constant for DAY_OF_YEAR field alignment.
  192. * Used in FieldPosition of date/time formatting.
  193. */
  194. public final static int DAY_OF_YEAR_FIELD = 10;
  195. /**
  196. * Useful constant for DAY_OF_WEEK_IN_MONTH field alignment.
  197. * Used in FieldPosition of date/time formatting.
  198. */
  199. public final static int DAY_OF_WEEK_IN_MONTH_FIELD = 11;
  200. /**
  201. * Useful constant for WEEK_OF_YEAR field alignment.
  202. * Used in FieldPosition of date/time formatting.
  203. */
  204. public final static int WEEK_OF_YEAR_FIELD = 12;
  205. /**
  206. * Useful constant for WEEK_OF_MONTH field alignment.
  207. * Used in FieldPosition of date/time formatting.
  208. */
  209. public final static int WEEK_OF_MONTH_FIELD = 13;
  210. /**
  211. * Useful constant for AM_PM field alignment.
  212. * Used in FieldPosition of date/time formatting.
  213. */
  214. public final static int AM_PM_FIELD = 14;
  215. /**
  216. * Useful constant for one-based HOUR field alignment.
  217. * Used in FieldPosition of date/time formatting.
  218. * HOUR1_FIELD is used for the one-based 12-hour clock.
  219. * For example, 11:30 PM + 1 hour results in 12:30 AM.
  220. */
  221. public final static int HOUR1_FIELD = 15;
  222. /**
  223. * Useful constant for zero-based HOUR field alignment.
  224. * Used in FieldPosition of date/time formatting.
  225. * HOUR0_FIELD is used for the zero-based 12-hour clock.
  226. * For example, 11:30 PM + 1 hour results in 00:30 AM.
  227. */
  228. public final static int HOUR0_FIELD = 16;
  229. /**
  230. * Useful constant for TIMEZONE field alignment.
  231. * Used in FieldPosition of date/time formatting.
  232. */
  233. public final static int TIMEZONE_FIELD = 17;
  234. // Proclaim serial compatibility with 1.1 FCS
  235. private static final long serialVersionUID = 7218322306649953788L;
  236. /**
  237. * Overrides Format.
  238. * Formats a time object into a time string. Examples of time objects
  239. * are a time value expressed in milliseconds and a Date object.
  240. * @param obj must be a Number or a Date.
  241. * @param toAppendTo the string buffer for the returning time string.
  242. * @return the formatted time string.
  243. * @param fieldPosition keeps track of the position of the field
  244. * within the returned string.
  245. * On input: an alignment field,
  246. * if desired. On output: the offsets of the alignment field. For
  247. * example, given a time text "1996.07.10 AD at 15:08:56 PDT",
  248. * if the given fieldPosition is DateFormat.YEAR_FIELD, the
  249. * begin index and end index of fieldPosition will be set to
  250. * 0 and 4, respectively.
  251. * Notice that if the same time field appears
  252. * more than once in a pattern, the fieldPosition will be set for the first
  253. * occurrence of that time field. For instance, formatting a Date to
  254. * the time string "1 PM PDT (Pacific Daylight Time)" using the pattern
  255. * "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,
  256. * the begin index and end index of fieldPosition will be set to
  257. * 5 and 8, respectively, for the first occurrence of the timezone
  258. * pattern character 'z'.
  259. * @see java.text.Format
  260. */
  261. public final StringBuffer format(Object obj, StringBuffer toAppendTo,
  262. FieldPosition fieldPosition)
  263. {
  264. if (obj instanceof Date)
  265. return format( (Date)obj, toAppendTo, fieldPosition );
  266. else if (obj instanceof Number)
  267. return format( new Date(((Number)obj).longValue()),
  268. toAppendTo, fieldPosition );
  269. else
  270. throw new IllegalArgumentException("Cannot format given Object as a Date");
  271. }
  272. /**
  273. * Formats a Date into a date/time string.
  274. * @param date a Date to be formatted into a date/time string.
  275. * @param toAppendTo the string buffer for the returning date/time string.
  276. * @param fieldPosition keeps track of the position of the field
  277. * within the returned string.
  278. * On input: an alignment field,
  279. * if desired. On output: the offsets of the alignment field. For
  280. * example, given a time text "1996.07.10 AD at 15:08:56 PDT",
  281. * if the given fieldPosition is DateFormat.YEAR_FIELD, the
  282. * begin index and end index of fieldPosition will be set to
  283. * 0 and 4, respectively.
  284. * Notice that if the same time field appears
  285. * more than once in a pattern, the fieldPosition will be set for the first
  286. * occurrence of that time field. For instance, formatting a Date to
  287. * the time string "1 PM PDT (Pacific Daylight Time)" using the pattern
  288. * "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,
  289. * the begin index and end index of fieldPosition will be set to
  290. * 5 and 8, respectively, for the first occurrence of the timezone
  291. * pattern character 'z'.
  292. * @return the formatted date/time string.
  293. */
  294. public abstract StringBuffer format(Date date, StringBuffer toAppendTo,
  295. FieldPosition fieldPosition);
  296. /**
  297. * Formats a Date into a date/time string.
  298. * @param date the time value to be formatted into a time string.
  299. * @return the formatted time string.
  300. */
  301. public final String format(Date date)
  302. {
  303. return format(date, new StringBuffer(),
  304. DontCareFieldPosition.INSTANCE).toString();
  305. }
  306. /**
  307. * Parses text from the beginning of the given string to produce a date.
  308. * The method may not use the entire text of the given string.
  309. * <p>
  310. * See the {@link #parse(String, ParsePosition)} method for more information
  311. * on date parsing.
  312. *
  313. * @param source A <code>String</code> whose beginning should be parsed.
  314. * @return A <code>Date</code> parsed from the string.
  315. * @exception ParseException if the beginning of the specified string
  316. * cannot be parsed.
  317. */
  318. public Date parse(String source) throws ParseException
  319. {
  320. ParsePosition pos = new ParsePosition(0);
  321. Date result = parse(source, pos);
  322. if (pos.index == 0)
  323. throw new ParseException("Unparseable date: \"" + source + "\"" ,
  324. pos.errorIndex);
  325. return result;
  326. }
  327. /**
  328. * Parse a date/time string according to the given parse position. For
  329. * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
  330. * that is equivalent to Date(837039928046).
  331. *
  332. * <p> By default, parsing is lenient: If the input is not in the form used
  333. * by this object's format method but can still be parsed as a date, then
  334. * the parse succeeds. Clients may insist on strict adherence to the
  335. * format by calling setLenient(false).
  336. *
  337. * @see java.text.DateFormat#setLenient(boolean)
  338. *
  339. * @param source The date/time string to be parsed
  340. *
  341. * @param pos On input, the position at which to start parsing; on
  342. * output, the position at which parsing terminated, or the
  343. * start position if the parse failed.
  344. *
  345. * @return A Date, or null if the input could not be parsed
  346. */
  347. public abstract Date parse(String source, ParsePosition pos);
  348. /**
  349. * Parses text from a string to produce a <code>Date</code>.
  350. * <p>
  351. * The method attempts to parse text starting at the index given by
  352. * <code>pos</code>.
  353. * If parsing succeeds, then the index of <code>pos</code> is updated
  354. * to the index after the last character used (parsing does not necessarily
  355. * use all characters up to the end of the string), and the parsed
  356. * date is returned. The updated <code>pos</code> can be used to
  357. * indicate the starting point for the next call to this method.
  358. * If an error occurs, then the index of <code>pos</code> is not
  359. * changed, the error index of <code>pos</code> is set to the index of
  360. * the character where the error occurred, and null is returned.
  361. * <p>
  362. * See the {@link #parse(String, ParsePosition)} method for more information
  363. * on date parsing.
  364. *
  365. * @param source A <code>String</code>, part of which should be parsed.
  366. * @param pos A <code>ParsePosition</code> object with index and error
  367. * index information as described above.
  368. * @return A <code>Date</code> parsed from the string. In case of
  369. * error, returns null.
  370. * @exception NullPointerException if <code>pos</code> is null.
  371. */
  372. public Object parseObject(String source, ParsePosition pos) {
  373. return parse(source, pos);
  374. }
  375. /**
  376. * Constant for full style pattern.
  377. */
  378. public static final int FULL = 0;
  379. /**
  380. * Constant for long style pattern.
  381. */
  382. public static final int LONG = 1;
  383. /**
  384. * Constant for medium style pattern.
  385. */
  386. public static final int MEDIUM = 2;
  387. /**
  388. * Constant for short style pattern.
  389. */
  390. public static final int SHORT = 3;
  391. /**
  392. * Constant for default style pattern. Its value is MEDIUM.
  393. */
  394. public static final int DEFAULT = MEDIUM;
  395. /**
  396. * Gets the time formatter with the default formatting style
  397. * for the default locale.
  398. * @return a time formatter.
  399. */
  400. public final static DateFormat getTimeInstance()
  401. {
  402. return get(DEFAULT, 0, 1, Locale.getDefault());
  403. }
  404. /**
  405. * Gets the time formatter with the given formatting style
  406. * for the default locale.
  407. * @param style the given formatting style. For example,
  408. * SHORT for "h:mm a" in the US locale.
  409. * @return a time formatter.
  410. */
  411. public final static DateFormat getTimeInstance(int style)
  412. {
  413. return get(style, 0, 1, Locale.getDefault());
  414. }
  415. /**
  416. * Gets the time formatter with the given formatting style
  417. * for the given locale.
  418. * @param style the given formatting style. For example,
  419. * SHORT for "h:mm a" in the US locale.
  420. * @param aLocale the given locale.
  421. * @return a time formatter.
  422. */
  423. public final static DateFormat getTimeInstance(int style,
  424. Locale aLocale)
  425. {
  426. return get(style, 0, 1, aLocale);
  427. }
  428. /**
  429. * Gets the date formatter with the default formatting style
  430. * for the default locale.
  431. * @return a date formatter.
  432. */
  433. public final static DateFormat getDateInstance()
  434. {
  435. return get(0, DEFAULT, 2, Locale.getDefault());
  436. }
  437. /**
  438. * Gets the date formatter with the given formatting style
  439. * for the default locale.
  440. * @param style the given formatting style. For example,
  441. * SHORT for "M/d/yy" in the US locale.
  442. * @return a date formatter.
  443. */
  444. public final static DateFormat getDateInstance(int style)
  445. {
  446. return get(0, style, 2, Locale.getDefault());
  447. }
  448. /**
  449. * Gets the date formatter with the given formatting style
  450. * for the given locale.
  451. * @param style the given formatting style. For example,
  452. * SHORT for "M/d/yy" in the US locale.
  453. * @param aLocale the given locale.
  454. * @return a date formatter.
  455. */
  456. public final static DateFormat getDateInstance(int style,
  457. Locale aLocale)
  458. {
  459. return get(0, style, 2, aLocale);
  460. }
  461. /**
  462. * Gets the date/time formatter with the default formatting style
  463. * for the default locale.
  464. * @return a date/time formatter.
  465. */
  466. public final static DateFormat getDateTimeInstance()
  467. {
  468. return get(DEFAULT, DEFAULT, 3, Locale.getDefault());
  469. }
  470. /**
  471. * Gets the date/time formatter with the given date and time
  472. * formatting styles for the default locale.
  473. * @param dateStyle the given date formatting style. For example,
  474. * SHORT for "M/d/yy" in the US locale.
  475. * @param timeStyle the given time formatting style. For example,
  476. * SHORT for "h:mm a" in the US locale.
  477. * @return a date/time formatter.
  478. */
  479. public final static DateFormat getDateTimeInstance(int dateStyle,
  480. int timeStyle)
  481. {
  482. return get(timeStyle, dateStyle, 3, Locale.getDefault());
  483. }
  484. /**
  485. * Gets the date/time formatter with the given formatting styles
  486. * for the given locale.
  487. * @param dateStyle the given date formatting style.
  488. * @param timeStyle the given time formatting style.
  489. * @param aLocale the given locale.
  490. * @return a date/time formatter.
  491. */
  492. public final static DateFormat
  493. getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale)
  494. {
  495. return get(timeStyle, dateStyle, 3, aLocale);
  496. }
  497. /**
  498. * Get a default date/time formatter that uses the SHORT style for both the
  499. * date and the time.
  500. */
  501. public final static DateFormat getInstance() {
  502. return getDateTimeInstance(SHORT, SHORT);
  503. }
  504. /**
  505. * Gets the set of locales for which DateFormats are installed.
  506. * @return the set of locales for which DateFormats are installed.
  507. */
  508. public static Locale[] getAvailableLocales()
  509. {
  510. return LocaleData.getAvailableLocales("DateTimePatterns");
  511. }
  512. /**
  513. * Set the calendar to be used by this date format. Initially, the default
  514. * calendar for the specified or default locale is used.
  515. * @param newCalendar the new Calendar to be used by the date format
  516. */
  517. public void setCalendar(Calendar newCalendar)
  518. {
  519. this.calendar = newCalendar;
  520. }
  521. /**
  522. * Gets the calendar associated with this date/time formatter.
  523. * @return the calendar associated with this date/time formatter.
  524. */
  525. public Calendar getCalendar()
  526. {
  527. return calendar;
  528. }
  529. /**
  530. * Allows you to set the number formatter.
  531. * @param newNumberFormat the given new NumberFormat.
  532. */
  533. public void setNumberFormat(NumberFormat newNumberFormat)
  534. {
  535. this.numberFormat = newNumberFormat;
  536. }
  537. /**
  538. * Gets the number formatter which this date/time formatter uses to
  539. * format and parse a time.
  540. * @return the number formatter which this date/time formatter uses.
  541. */
  542. public NumberFormat getNumberFormat()
  543. {
  544. return numberFormat;
  545. }
  546. /**
  547. * Sets the time zone for the calendar of this DateFormat object.
  548. * @param zone the given new time zone.
  549. */
  550. public void setTimeZone(TimeZone zone)
  551. {
  552. calendar.setTimeZone(zone);
  553. }
  554. /**
  555. * Gets the time zone.
  556. * @return the time zone associated with the calendar of DateFormat.
  557. */
  558. public TimeZone getTimeZone()
  559. {
  560. return calendar.getTimeZone();
  561. }
  562. /**
  563. * Specify whether or not date/time parsing is to be lenient. With
  564. * lenient parsing, the parser may use heuristics to interpret inputs that
  565. * do not precisely match this object's format. With strict parsing,
  566. * inputs must match this object's format.
  567. * @param lenient when true, parsing is lenient
  568. * @see java.util.Calendar#setLenient
  569. */
  570. public void setLenient(boolean lenient)
  571. {
  572. calendar.setLenient(lenient);
  573. }
  574. /**
  575. * Tell whether date/time parsing is to be lenient.
  576. */
  577. public boolean isLenient()
  578. {
  579. return calendar.isLenient();
  580. }
  581. /**
  582. * Overrides hashCode
  583. */
  584. public int hashCode() {
  585. return numberFormat.hashCode();
  586. // just enough fields for a reasonable distribution
  587. }
  588. /**
  589. * Overrides equals
  590. */
  591. public boolean equals(Object obj) {
  592. if (this == obj) return true;
  593. if (obj == null || getClass() != obj.getClass()) return false;
  594. DateFormat other = (DateFormat) obj;
  595. return (// calendar.equivalentTo(other.calendar) // THIS API DOESN'T EXIST YET!
  596. calendar.getFirstDayOfWeek() == other.calendar.getFirstDayOfWeek() &&
  597. calendar.getMinimalDaysInFirstWeek() == other.calendar.getMinimalDaysInFirstWeek() &&
  598. calendar.isLenient() == other.calendar.isLenient() &&
  599. calendar.getTimeZone().equals(other.calendar.getTimeZone()) &&
  600. numberFormat.equals(other.numberFormat));
  601. }
  602. /**
  603. * Overrides Cloneable
  604. */
  605. public Object clone()
  606. {
  607. DateFormat other = (DateFormat) super.clone();
  608. other.calendar = (Calendar) calendar.clone();
  609. other.numberFormat = (NumberFormat) numberFormat.clone();
  610. return other;
  611. }
  612. /**
  613. * Creates a DateFormat with the given time and/or date style in the given
  614. * locale.
  615. * @param timeStyle a value from 0 to 3 indicating the time format,
  616. * ignored if flags is 2
  617. * @param dateStyle a value from 0 to 3 indicating the time format,
  618. * ignored if flags is 1
  619. * @param flags either 1 for a time format, 2 for a date format,
  620. * or 3 for a date/time format
  621. * @param loc the locale for the format
  622. */
  623. private static DateFormat get(int timeStyle, int dateStyle,
  624. int flags, Locale loc) {
  625. if ((flags & 1) != 0) {
  626. if (timeStyle < 0 || timeStyle > 3) {
  627. throw new IllegalArgumentException("Illegal time style " + timeStyle);
  628. }
  629. } else {
  630. timeStyle = -1;
  631. }
  632. if ((flags & 2) != 0) {
  633. if (dateStyle < 0 || dateStyle > 3) {
  634. throw new IllegalArgumentException("Illegal date style " + dateStyle);
  635. }
  636. } else {
  637. dateStyle = -1;
  638. }
  639. try {
  640. return new SimpleDateFormat(timeStyle, dateStyle, loc);
  641. } catch (MissingResourceException e) {
  642. return new SimpleDateFormat("M/d/yy h:mm a");
  643. }
  644. }
  645. /**
  646. * Create a new date format.
  647. */
  648. protected DateFormat() {}
  649. /**
  650. * Defines constants that are used as attribute keys in the
  651. * <code>AttributedCharacterIterator</code> returned
  652. * from <code>DateFormat.formatToCharacterIterator</code> and as
  653. * field identifiers in <code>FieldPosition</code>.
  654. * <p>
  655. * The class also provides two methods to map
  656. * between its constants and the corresponding Calendar constants.
  657. *
  658. * @since 1.4
  659. * @see java.util.Calendar
  660. */
  661. public static class Field extends Format.Field {
  662. // table of all instances in this class, used by readResolve
  663. private static final Map instanceMap = new HashMap(18);
  664. // Maps from Calendar constant (such as Calendar.ERA) to Field
  665. // constant (such as Field.ERA).
  666. private static final Field[] calendarToFieldMapping =
  667. new Field[Calendar.FIELD_COUNT];
  668. /** Calendar field. */
  669. private int calendarField;
  670. /**
  671. * Returns the <code>Field</code> constant that corresponds to
  672. * the <code>Calendar</code> constant <code>calendarField</code>.
  673. * If there is no direct mapping between the <code>Calendar</code>
  674. * constant and a <code>Field</code>, null is returned.
  675. *
  676. * @throws IllegalArgumentException if <code>calendarField</code> is
  677. * not the value of a <code>Calendar</code> field constant.
  678. * @param calendarField Calendar field constant
  679. * @return Field instance representing calendarField.
  680. * @see java.util.Calendar
  681. */
  682. public static Field ofCalendarField(int calendarField) {
  683. if (calendarField < 0 || calendarField >=
  684. calendarToFieldMapping.length) {
  685. throw new IllegalArgumentException("Unknown Calendar constant "
  686. + calendarField);
  687. }
  688. return calendarToFieldMapping[calendarField];
  689. }
  690. /**
  691. * Creates a Field with the specified name.
  692. * calendarField is used to identify the <code>Calendar</code>
  693. * field this attribute represents. Use -1 if this field does
  694. * not have a corresponding <code>Calendar</code> value.
  695. *
  696. * @param name Name of the attribute
  697. * @param calendarField Calendar constant
  698. */
  699. protected Field(String name, int calendarField) {
  700. super(name);
  701. this.calendarField = calendarField;
  702. if (this.getClass() == DateFormat.Field.class) {
  703. instanceMap.put(name, this);
  704. if (calendarField >= 0) {
  705. // assert(calendarField < Calendar.FIELD_COUNT);
  706. calendarToFieldMapping[calendarField] = this;
  707. }
  708. }
  709. }
  710. /**
  711. * Returns the <code>Calendar</code> field associated with this
  712. * attribute. For example, if this represents the hours field of
  713. * a <code>Calendar</code>, this would return
  714. * <code>Calendar.HOUR</code>. If there is no corresponding
  715. * <code>Calendar</code> constant, this will return -1.
  716. *
  717. * @return Calendar constant for this field
  718. * @see java.util.Calendar
  719. */
  720. public int getCalendarField() {
  721. return calendarField;
  722. }
  723. /**
  724. * Resolves instances being deserialized to the predefined constants.
  725. *
  726. * @throws InvalidObjectException if the constant could not be
  727. * resolved.
  728. * @return resolved DateFormat.Field constant
  729. */
  730. protected Object readResolve() throws InvalidObjectException {
  731. if (this.getClass() != DateFormat.Field.class) {
  732. throw new InvalidObjectException("subclass didn't correctly implement readResolve");
  733. }
  734. Object instance = instanceMap.get(getName());
  735. if (instance != null) {
  736. return instance;
  737. } else {
  738. throw new InvalidObjectException("unknown attribute name");
  739. }
  740. }
  741. //
  742. // The constants
  743. //
  744. /**
  745. * Constant identifying the era field.
  746. */
  747. public final static Field ERA = new Field("era", Calendar.ERA);
  748. /**
  749. * Constant identifying the year field.
  750. */
  751. public final static Field YEAR = new Field("year", Calendar.YEAR);
  752. /**
  753. * Constant identifying the month field.
  754. */
  755. public final static Field MONTH = new Field("month", Calendar.MONTH);
  756. /**
  757. * Constant identifying the day of month field.
  758. */
  759. public final static Field DAY_OF_MONTH = new
  760. Field("day of month", Calendar.DAY_OF_MONTH);
  761. /**
  762. * Constant identifying the hour of day field, where the legal values
  763. * are 1 to 24.
  764. */
  765. public final static Field HOUR_OF_DAY1 = new Field("hour of day 1",-1);
  766. /**
  767. * Constant identifying the hour of day field, where the legal values
  768. * are 0 to 23.
  769. */
  770. public final static Field HOUR_OF_DAY0 = new
  771. Field("hour of day", Calendar.HOUR_OF_DAY);
  772. /**
  773. * Constant identifying the minute field.
  774. */
  775. public final static Field MINUTE =new Field("minute", Calendar.MINUTE);
  776. /**
  777. * Constant identifying the second field.
  778. */
  779. public final static Field SECOND =new Field("second", Calendar.SECOND);
  780. /**
  781. * Constant identifying the millisecond field.
  782. */
  783. public final static Field MILLISECOND = new
  784. Field("millisecond", Calendar.MILLISECOND);
  785. /**
  786. * Constant identifying the day of week field.
  787. */
  788. public final static Field DAY_OF_WEEK = new
  789. Field("day of week", Calendar.DAY_OF_WEEK);
  790. /**
  791. * Constant identifying the day of year field.
  792. */
  793. public final static Field DAY_OF_YEAR = new
  794. Field("day of year", Calendar.DAY_OF_YEAR);
  795. /**
  796. * Constant identifying the day of week field.
  797. */
  798. public final static Field DAY_OF_WEEK_IN_MONTH =
  799. new Field("day of week in month",
  800. Calendar.DAY_OF_WEEK_IN_MONTH);
  801. /**
  802. * Constant identifying the week of year field.
  803. */
  804. public final static Field WEEK_OF_YEAR = new
  805. Field("week of year", Calendar.WEEK_OF_YEAR);
  806. /**
  807. * Constant identifying the week of month field.
  808. */
  809. public final static Field WEEK_OF_MONTH = new
  810. Field("week of month", Calendar.WEEK_OF_MONTH);
  811. /**
  812. * Constant identifying the time of day indicator
  813. * (e.g. "a.m." or "p.m.") field.
  814. */
  815. public final static Field AM_PM = new
  816. Field("am pm", Calendar.AM_PM);
  817. /**
  818. * Constant identifying the hour field, where the legal values are
  819. * 1 to 12.
  820. */
  821. public final static Field HOUR1 = new Field("hour 1", -1);
  822. /**
  823. * Constant identifying the hour field, where the legal values are
  824. * 0 to 11.
  825. */
  826. public final static Field HOUR0 = new
  827. Field("hour", Calendar.HOUR);
  828. /**
  829. * Constant identifying the time zone field.
  830. */
  831. public final static Field TIME_ZONE = new Field("time zone", -1);
  832. }
  833. }