KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > text > DateFormat


1 /*
2  * @(#)DateFormat.java 1.51 04/04/12
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 /*
9  * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
10  * (C) Copyright IBM Corp. 1996 - All Rights Reserved
11  *
12  * The original version of this source code and documentation is copyrighted
13  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
14  * materials are provided under terms of a License Agreement between Taligent
15  * and Sun. This technology is protected by multiple US and International
16  * patents. This notice and attribution to Taligent may not be removed.
17  * Taligent is a registered trademark of Taligent, Inc.
18  *
19  */

20
21 package java.text;
22
23 import java.io.InvalidObjectException JavaDoc;
24 import java.util.HashMap JavaDoc;
25 import java.util.Locale JavaDoc;
26 import java.util.Map JavaDoc;
27 import java.util.ResourceBundle JavaDoc;
28 import java.util.MissingResourceException JavaDoc;
29 import java.util.TimeZone JavaDoc;
30 import java.util.Calendar JavaDoc;
31 import java.util.GregorianCalendar JavaDoc;
32 import java.util.Date JavaDoc;
33 import sun.text.resources.LocaleData;
34
35 /**
36  * DateFormat is an abstract class for date/time formatting subclasses which
37  * formats and parses dates or time in a language-independent manner.
38  * The date/time formatting subclass, such as SimpleDateFormat, allows for
39  * formatting (i.e., date -> text), parsing (text -> date), and
40  * normalization. The date is represented as a <code>Date</code> object or
41  * as the milliseconds since January 1, 1970, 00:00:00 GMT.
42  *
43  * <p>DateFormat provides many class methods for obtaining default date/time
44  * formatters based on the default or a given locale and a number of formatting
45  * styles. The formatting styles include FULL, LONG, MEDIUM, and SHORT. More
46  * detail and examples of using these styles are provided in the method
47  * descriptions.
48  *
49  * <p>DateFormat helps you to format and parse dates for any locale.
50  * Your code can be completely independent of the locale conventions for
51  * months, days of the week, or even the calendar format: lunar vs. solar.
52  *
53  * <p>To format a date for the current Locale, use one of the
54  * static factory methods:
55  * <pre>
56  * myString = DateFormat.getDateInstance().format(myDate);
57  * </pre>
58  * <p>If you are formatting multiple dates, it is
59  * more efficient to get the format and use it multiple times so that
60  * the system doesn't have to fetch the information about the local
61  * language and country conventions multiple times.
62  * <pre>
63  * DateFormat df = DateFormat.getDateInstance();
64  * for (int i = 0; i < myDate.length; ++i) {
65  * output.println(df.format(myDate[i]) + "; ");
66  * }
67  * </pre>
68  * <p>To format a date for a different Locale, specify it in the
69  * call to getDateInstance().
70  * <pre>
71  * DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
72  * </pre>
73  * <p>You can use a DateFormat to parse also.
74  * <pre>
75  * myDate = df.parse(myString);
76  * </pre>
77  * <p>Use getDateInstance to get the normal date format for that country.
78  * There are other static factory methods available.
79  * Use getTimeInstance to get the time format for that country.
80  * Use getDateTimeInstance to get a date and time format. You can pass in
81  * different options to these factory methods to control the length of the
82  * result; from SHORT to MEDIUM to LONG to FULL. The exact result depends
83  * on the locale, but generally:
84  * <ul><li>SHORT is completely numeric, such as 12.13.52 or 3:30pm
85  * <li>MEDIUM is longer, such as Jan 12, 1952
86  * <li>LONG is longer, such as January 12, 1952 or 3:30:32pm
87  * <li>FULL is pretty completely specified, such as
88  * Tuesday, April 12, 1952 AD or 3:30:42pm PST.
89  * </ul>
90  *
91  * <p>You can also set the time zone on the format if you wish.
92  * If you want even more control over the format or parsing,
93  * (or want to give your users more control),
94  * you can try casting the DateFormat you get from the factory methods
95  * to a SimpleDateFormat. This will work for the majority
96  * of countries; just remember to put it in a try block in case you
97  * encounter an unusual one.
98  *
99  * <p>You can also use forms of the parse and format methods with
100  * ParsePosition and FieldPosition to
101  * allow you to
102  * <ul><li>progressively parse through pieces of a string.
103  * <li>align any particular field, or find out where it is for selection
104  * on the screen.
105  * </ul>
106  *
107  * <h4><a name="synchronization">Synchronization</a></h4>
108  *
109  * <p>
110  * Date formats are not synchronized.
111  * It is recommended to create separate format instances for each thread.
112  * If multiple threads access a format concurrently, it must be synchronized
113  * externally.
114  *
115  * @see Format
116  * @see NumberFormat
117  * @see SimpleDateFormat
118  * @see java.util.Calendar
119  * @see java.util.GregorianCalendar
120  * @see java.util.TimeZone
121  * @version 1.51 04/12/04
122  * @author Mark Davis, Chen-Lieh Huang, Alan Liu
123  */

124 public abstract class DateFormat extends Format JavaDoc {
125
126     /**
127      * The calendar that <code>DateFormat</code> uses to produce the time field
128      * values needed to implement date and time formatting. Subclasses should
129      * initialize this to a calendar appropriate for the locale associated with
130      * this <code>DateFormat</code>.
131      * @serial
132      */

133     protected Calendar JavaDoc calendar;
134
135     /**
136      * The number formatter that <code>DateFormat</code> uses to format numbers
137      * in dates and times. Subclasses should initialize this to a number format
138      * appropriate for the locale associated with this <code>DateFormat</code>.
139      * @serial
140      */

141     protected NumberFormat JavaDoc numberFormat;
142
143     /**
144      * Useful constant for ERA field alignment.
145      * Used in FieldPosition of date/time formatting.
146      */

147     public final static int ERA_FIELD = 0;
148     /**
149      * Useful constant for YEAR field alignment.
150      * Used in FieldPosition of date/time formatting.
151      */

152     public final static int YEAR_FIELD = 1;
153     /**
154      * Useful constant for MONTH field alignment.
155      * Used in FieldPosition of date/time formatting.
156      */

157     public final static int MONTH_FIELD = 2;
158     /**
159      * Useful constant for DATE field alignment.
160      * Used in FieldPosition of date/time formatting.
161      */

162     public final static int DATE_FIELD = 3;
163     /**
164      * Useful constant for one-based HOUR_OF_DAY field alignment.
165      * Used in FieldPosition of date/time formatting.
166      * HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock.
167      * For example, 23:59 + 01:00 results in 24:59.
168      */

169     public final static int HOUR_OF_DAY1_FIELD = 4;
170     /**
171      * Useful constant for zero-based HOUR_OF_DAY field alignment.
172      * Used in FieldPosition of date/time formatting.
173      * HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock.
174      * For example, 23:59 + 01:00 results in 00:59.
175      */

176     public final static int HOUR_OF_DAY0_FIELD = 5;
177     /**
178      * Useful constant for MINUTE field alignment.
179      * Used in FieldPosition of date/time formatting.
180      */

181     public final static int MINUTE_FIELD = 6;
182     /**
183      * Useful constant for SECOND field alignment.
184      * Used in FieldPosition of date/time formatting.
185      */

186     public final static int SECOND_FIELD = 7;
187     /**
188      * Useful constant for MILLISECOND field alignment.
189      * Used in FieldPosition of date/time formatting.
190      */

191     public final static int MILLISECOND_FIELD = 8;
192     /**
193      * Useful constant for DAY_OF_WEEK field alignment.
194      * Used in FieldPosition of date/time formatting.
195      */

196     public final static int DAY_OF_WEEK_FIELD = 9;
197     /**
198      * Useful constant for DAY_OF_YEAR field alignment.
199      * Used in FieldPosition of date/time formatting.
200      */

201     public final static int DAY_OF_YEAR_FIELD = 10;
202     /**
203      * Useful constant for DAY_OF_WEEK_IN_MONTH field alignment.
204      * Used in FieldPosition of date/time formatting.
205      */

206     public final static int DAY_OF_WEEK_IN_MONTH_FIELD = 11;
207     /**
208      * Useful constant for WEEK_OF_YEAR field alignment.
209      * Used in FieldPosition of date/time formatting.
210      */

211     public final static int WEEK_OF_YEAR_FIELD = 12;
212     /**
213      * Useful constant for WEEK_OF_MONTH field alignment.
214      * Used in FieldPosition of date/time formatting.
215      */

216     public final static int WEEK_OF_MONTH_FIELD = 13;
217     /**
218      * Useful constant for AM_PM field alignment.
219      * Used in FieldPosition of date/time formatting.
220      */

221     public final static int AM_PM_FIELD = 14;
222     /**
223      * Useful constant for one-based HOUR field alignment.
224      * Used in FieldPosition of date/time formatting.
225      * HOUR1_FIELD is used for the one-based 12-hour clock.
226      * For example, 11:30 PM + 1 hour results in 12:30 AM.
227      */

228     public final static int HOUR1_FIELD = 15;
229     /**
230      * Useful constant for zero-based HOUR field alignment.
231      * Used in FieldPosition of date/time formatting.
232      * HOUR0_FIELD is used for the zero-based 12-hour clock.
233      * For example, 11:30 PM + 1 hour results in 00:30 AM.
234      */

235     public final static int HOUR0_FIELD = 16;
236     /**
237      * Useful constant for TIMEZONE field alignment.
238      * Used in FieldPosition of date/time formatting.
239      */

240     public final static int TIMEZONE_FIELD = 17;
241
242     // Proclaim serial compatibility with 1.1 FCS
243
private static final long serialVersionUID = 7218322306649953788L;
244
245     /**
246      * Overrides Format.
247      * Formats a time object into a time string. Examples of time objects
248      * are a time value expressed in milliseconds and a Date object.
249      * @param obj must be a Number or a Date.
250      * @param toAppendTo the string buffer for the returning time string.
251      * @return the formatted time string.
252      * @param fieldPosition keeps track of the position of the field
253      * within the returned string.
254      * On input: an alignment field,
255      * if desired. On output: the offsets of the alignment field. For
256      * example, given a time text "1996.07.10 AD at 15:08:56 PDT",
257      * if the given fieldPosition is DateFormat.YEAR_FIELD, the
258      * begin index and end index of fieldPosition will be set to
259      * 0 and 4, respectively.
260      * Notice that if the same time field appears
261      * more than once in a pattern, the fieldPosition will be set for the first
262      * occurrence of that time field. For instance, formatting a Date to
263      * the time string "1 PM PDT (Pacific Daylight Time)" using the pattern
264      * "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,
265      * the begin index and end index of fieldPosition will be set to
266      * 5 and 8, respectively, for the first occurrence of the timezone
267      * pattern character 'z'.
268      * @see java.text.Format
269      */

270     public final StringBuffer JavaDoc format(Object JavaDoc obj, StringBuffer JavaDoc toAppendTo,
271                                      FieldPosition JavaDoc fieldPosition)
272     {
273         if (obj instanceof Date JavaDoc)
274             return format( (Date JavaDoc)obj, toAppendTo, fieldPosition );
275         else if (obj instanceof Number JavaDoc)
276             return format( new Date JavaDoc(((Number JavaDoc)obj).longValue()),
277                           toAppendTo, fieldPosition );
278         else
279             throw new IllegalArgumentException JavaDoc("Cannot format given Object as a Date");
280     }
281
282     /**
283      * Formats a Date into a date/time string.
284      * @param date a Date to be formatted into a date/time string.
285      * @param toAppendTo the string buffer for the returning date/time string.
286      * @param fieldPosition keeps track of the position of the field
287      * within the returned string.
288      * On input: an alignment field,
289      * if desired. On output: the offsets of the alignment field. For
290      * example, given a time text "1996.07.10 AD at 15:08:56 PDT",
291      * if the given fieldPosition is DateFormat.YEAR_FIELD, the
292      * begin index and end index of fieldPosition will be set to
293      * 0 and 4, respectively.
294      * Notice that if the same time field appears
295      * more than once in a pattern, the fieldPosition will be set for the first
296      * occurrence of that time field. For instance, formatting a Date to
297      * the time string "1 PM PDT (Pacific Daylight Time)" using the pattern
298      * "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,
299      * the begin index and end index of fieldPosition will be set to
300      * 5 and 8, respectively, for the first occurrence of the timezone
301      * pattern character 'z'.
302      * @return the formatted date/time string.
303      */

304     public abstract StringBuffer JavaDoc format(Date JavaDoc date, StringBuffer JavaDoc toAppendTo,
305                                         FieldPosition JavaDoc fieldPosition);
306
307     /**
308      * Formats a Date into a date/time string.
309      * @param date the time value to be formatted into a time string.
310      * @return the formatted time string.
311      */

312     public final String JavaDoc format(Date JavaDoc date)
313     {
314         return format(date, new StringBuffer JavaDoc(),
315               DontCareFieldPosition.INSTANCE).toString();
316     }
317
318     /**
319      * Parses text from the beginning of the given string to produce a date.
320      * The method may not use the entire text of the given string.
321      * <p>
322      * See the {@link #parse(String, ParsePosition)} method for more information
323      * on date parsing.
324      *
325      * @param source A <code>String</code> whose beginning should be parsed.
326      * @return A <code>Date</code> parsed from the string.
327      * @exception ParseException if the beginning of the specified string
328      * cannot be parsed.
329      */

330     public Date JavaDoc parse(String JavaDoc source) throws ParseException JavaDoc
331     {
332         ParsePosition JavaDoc pos = new ParsePosition JavaDoc(0);
333         Date JavaDoc result = parse(source, pos);
334         if (pos.index == 0)
335             throw new ParseException JavaDoc("Unparseable date: \"" + source + "\"" ,
336                 pos.errorIndex);
337         return result;
338     }
339
340     /**
341      * Parse a date/time string according to the given parse position. For
342      * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
343      * that is equivalent to Date(837039928046).
344      *
345      * <p> By default, parsing is lenient: If the input is not in the form used
346      * by this object's format method but can still be parsed as a date, then
347      * the parse succeeds. Clients may insist on strict adherence to the
348      * format by calling setLenient(false).
349      *
350      * @see java.text.DateFormat#setLenient(boolean)
351      *
352      * @param source The date/time string to be parsed
353      *
354      * @param pos On input, the position at which to start parsing; on
355      * output, the position at which parsing terminated, or the
356      * start position if the parse failed.
357      *
358      * @return A Date, or null if the input could not be parsed
359      */

360     public abstract Date JavaDoc parse(String JavaDoc source, ParsePosition JavaDoc pos);
361
362     /**
363      * Parses text from a string to produce a <code>Date</code>.
364      * <p>
365      * The method attempts to parse text starting at the index given by
366      * <code>pos</code>.
367      * If parsing succeeds, then the index of <code>pos</code> is updated
368      * to the index after the last character used (parsing does not necessarily
369      * use all characters up to the end of the string), and the parsed
370      * date is returned. The updated <code>pos</code> can be used to
371      * indicate the starting point for the next call to this method.
372      * If an error occurs, then the index of <code>pos</code> is not
373      * changed, the error index of <code>pos</code> is set to the index of
374      * the character where the error occurred, and null is returned.
375      * <p>
376      * See the {@link #parse(String, ParsePosition)} method for more information
377      * on date parsing.
378      *
379      * @param source A <code>String</code>, part of which should be parsed.
380      * @param pos A <code>ParsePosition</code> object with index and error
381      * index information as described above.
382      * @return A <code>Date</code> parsed from the string. In case of
383      * error, returns null.
384      * @exception NullPointerException if <code>pos</code> is null.
385      */

386     public Object JavaDoc parseObject(String JavaDoc source, ParsePosition JavaDoc pos) {
387         return parse(source, pos);
388     }
389
390     /**
391      * Constant for full style pattern.
392      */

393     public static final int FULL = 0;
394     /**
395      * Constant for long style pattern.
396      */

397     public static final int LONG = 1;
398     /**
399      * Constant for medium style pattern.
400      */

401     public static final int MEDIUM = 2;
402     /**
403      * Constant for short style pattern.
404      */

405     public static final int SHORT = 3;
406     /**
407      * Constant for default style pattern. Its value is MEDIUM.
408      */

409     public static final int DEFAULT = MEDIUM;
410
411     /**
412      * Gets the time formatter with the default formatting style
413      * for the default locale.
414      * @return a time formatter.
415      */

416     public final static DateFormat JavaDoc getTimeInstance()
417     {
418         return get(DEFAULT, 0, 1, Locale.getDefault());
419     }
420
421     /**
422      * Gets the time formatter with the given formatting style
423      * for the default locale.
424      * @param style the given formatting style. For example,
425      * SHORT for "h:mm a" in the US locale.
426      * @return a time formatter.
427      */

428     public final static DateFormat JavaDoc getTimeInstance(int style)
429     {
430         return get(style, 0, 1, Locale.getDefault());
431     }
432
433     /**
434      * Gets the time formatter with the given formatting style
435      * for the given locale.
436      * @param style the given formatting style. For example,
437      * SHORT for "h:mm a" in the US locale.
438      * @param aLocale the given locale.
439      * @return a time formatter.
440      */

441     public final static DateFormat JavaDoc getTimeInstance(int style,
442                                                  Locale JavaDoc aLocale)
443     {
444         return get(style, 0, 1, aLocale);
445     }
446
447     /**
448      * Gets the date formatter with the default formatting style
449      * for the default locale.
450      * @return a date formatter.
451      */

452     public final static DateFormat JavaDoc getDateInstance()
453     {
454         return get(0, DEFAULT, 2, Locale.getDefault());
455     }
456
457     /**
458      * Gets the date formatter with the given formatting style
459      * for the default locale.
460      * @param style the given formatting style. For example,
461      * SHORT for "M/d/yy" in the US locale.
462      * @return a date formatter.
463      */

464     public final static DateFormat JavaDoc getDateInstance(int style)
465     {
466         return get(0, style, 2, Locale.getDefault());
467     }
468
469     /**
470      * Gets the date formatter with the given formatting style
471      * for the given locale.
472      * @param style the given formatting style. For example,
473      * SHORT for "M/d/yy" in the US locale.
474      * @param aLocale the given locale.
475      * @return a date formatter.
476      */

477     public final static DateFormat JavaDoc getDateInstance(int style,
478                                                  Locale JavaDoc aLocale)
479     {
480         return get(0, style, 2, aLocale);
481     }
482
483     /**
484      * Gets the date/time formatter with the default formatting style
485      * for the default locale.
486      * @return a date/time formatter.
487      */

488     public final static DateFormat JavaDoc getDateTimeInstance()
489     {
490         return get(DEFAULT, DEFAULT, 3, Locale.getDefault());
491     }
492
493     /**
494      * Gets the date/time formatter with the given date and time
495      * formatting styles for the default locale.
496      * @param dateStyle the given date formatting style. For example,
497      * SHORT for "M/d/yy" in the US locale.
498      * @param timeStyle the given time formatting style. For example,
499      * SHORT for "h:mm a" in the US locale.
500      * @return a date/time formatter.
501      */

502     public final static DateFormat JavaDoc getDateTimeInstance(int dateStyle,
503                                                        int timeStyle)
504     {
505         return get(timeStyle, dateStyle, 3, Locale.getDefault());
506     }
507
508     /**
509      * Gets the date/time formatter with the given formatting styles
510      * for the given locale.
511      * @param dateStyle the given date formatting style.
512      * @param timeStyle the given time formatting style.
513      * @param aLocale the given locale.
514      * @return a date/time formatter.
515      */

516     public final static DateFormat JavaDoc
517         getDateTimeInstance(int dateStyle, int timeStyle, Locale JavaDoc aLocale)
518     {
519         return get(timeStyle, dateStyle, 3, aLocale);
520     }
521
522     /**
523      * Get a default date/time formatter that uses the SHORT style for both the
524      * date and the time.
525      */

526     public final static DateFormat JavaDoc getInstance() {
527         return getDateTimeInstance(SHORT, SHORT);
528     }
529
530     /**
531      * Returns an array of all locales for which the
532      * <code>get*Instance</code> methods of this class can return
533      * localized instances.
534      * The array returned must contain at least a <code>Locale</code>
535      * instance equal to {@link java.util.Locale#US Locale.US}.
536      *
537      * @return An array of locales for which localized
538      * <code>DateFormat</code> instances are available.
539      */

540     public static Locale JavaDoc[] getAvailableLocales()
541     {
542         return LocaleData.getAvailableLocales("DateTimePatterns");
543     }
544
545     /**
546      * Set the calendar to be used by this date format. Initially, the default
547      * calendar for the specified or default locale is used.
548      * @param newCalendar the new Calendar to be used by the date format
549      */

550     public void setCalendar(Calendar JavaDoc newCalendar)
551     {
552         this.calendar = newCalendar;
553     }
554
555     /**
556      * Gets the calendar associated with this date/time formatter.
557      * @return the calendar associated with this date/time formatter.
558      */

559     public Calendar JavaDoc getCalendar()
560     {
561         return calendar;
562     }
563
564     /**
565      * Allows you to set the number formatter.
566      * @param newNumberFormat the given new NumberFormat.
567      */

568     public void setNumberFormat(NumberFormat JavaDoc newNumberFormat)
569     {
570         this.numberFormat = newNumberFormat;
571     }
572
573     /**
574      * Gets the number formatter which this date/time formatter uses to
575      * format and parse a time.
576      * @return the number formatter which this date/time formatter uses.
577      */

578     public NumberFormat JavaDoc getNumberFormat()
579     {
580         return numberFormat;
581     }
582
583     /**
584      * Sets the time zone for the calendar of this DateFormat object.
585      * @param zone the given new time zone.
586      */

587     public void setTimeZone(TimeZone JavaDoc zone)
588     {
589         calendar.setTimeZone(zone);
590     }
591
592     /**
593      * Gets the time zone.
594      * @return the time zone associated with the calendar of DateFormat.
595      */

596     public TimeZone JavaDoc getTimeZone()
597     {
598         return calendar.getTimeZone();
599     }
600
601     /**
602      * Specify whether or not date/time parsing is to be lenient. With
603      * lenient parsing, the parser may use heuristics to interpret inputs that
604      * do not precisely match this object's format. With strict parsing,
605      * inputs must match this object's format.
606      * @param lenient when true, parsing is lenient
607      * @see java.util.Calendar#setLenient
608      */

609     public void setLenient(boolean lenient)
610     {
611         calendar.setLenient(lenient);
612     }
613
614     /**
615      * Tell whether date/time parsing is to be lenient.
616      */

617     public boolean isLenient()
618     {
619         return calendar.isLenient();
620     }
621
622     /**
623      * Overrides hashCode
624      */

625     public int hashCode() {
626         return numberFormat.hashCode();
627         // just enough fields for a reasonable distribution
628
}
629
630     /**
631      * Overrides equals
632      */

633     public boolean equals(Object JavaDoc obj) {
634         if (this == obj) return true;
635         if (obj == null || getClass() != obj.getClass()) return false;
636         DateFormat JavaDoc other = (DateFormat JavaDoc) obj;
637         return (// calendar.equivalentTo(other.calendar) // THIS API DOESN'T EXIST YET!
638
calendar.getFirstDayOfWeek() == other.calendar.getFirstDayOfWeek() &&
639                 calendar.getMinimalDaysInFirstWeek() == other.calendar.getMinimalDaysInFirstWeek() &&
640                 calendar.isLenient() == other.calendar.isLenient() &&
641                 calendar.getTimeZone().equals(other.calendar.getTimeZone()) &&
642                 numberFormat.equals(other.numberFormat));
643     }
644
645     /**
646      * Overrides Cloneable
647      */

648     public Object JavaDoc clone()
649     {
650         DateFormat JavaDoc other = (DateFormat JavaDoc) super.clone();
651         other.calendar = (Calendar JavaDoc) calendar.clone();
652         other.numberFormat = (NumberFormat JavaDoc) numberFormat.clone();
653         return other;
654     }
655
656     /**
657      * Creates a DateFormat with the given time and/or date style in the given
658      * locale.
659      * @param timeStyle a value from 0 to 3 indicating the time format,
660      * ignored if flags is 2
661      * @param dateStyle a value from 0 to 3 indicating the time format,
662      * ignored if flags is 1
663      * @param flags either 1 for a time format, 2 for a date format,
664      * or 3 for a date/time format
665      * @param loc the locale for the format
666      */

667     private static DateFormat JavaDoc get(int timeStyle, int dateStyle,
668                                   int flags, Locale JavaDoc loc) {
669         if ((flags & 1) != 0) {
670             if (timeStyle < 0 || timeStyle > 3) {
671                 throw new IllegalArgumentException JavaDoc("Illegal time style " + timeStyle);
672             }
673         } else {
674             timeStyle = -1;
675         }
676         if ((flags & 2) != 0) {
677             if (dateStyle < 0 || dateStyle > 3) {
678                 throw new IllegalArgumentException JavaDoc("Illegal date style " + dateStyle);
679             }
680         } else {
681             dateStyle = -1;
682         }
683         try {
684             return new SimpleDateFormat JavaDoc(timeStyle, dateStyle, loc);
685
686         } catch (MissingResourceException JavaDoc e) {
687             return new SimpleDateFormat JavaDoc("M/d/yy h:mm a");
688         }
689     }
690
691     /**
692      * Create a new date format.
693      */

694     protected DateFormat() {}
695
696     /**
697      * Defines constants that are used as attribute keys in the
698      * <code>AttributedCharacterIterator</code> returned
699      * from <code>DateFormat.formatToCharacterIterator</code> and as
700      * field identifiers in <code>FieldPosition</code>.
701      * <p>
702      * The class also provides two methods to map
703      * between its constants and the corresponding Calendar constants.
704      *
705      * @since 1.4
706      * @see java.util.Calendar
707      */

708     public static class Field extends Format.Field JavaDoc {
709
710         // Proclaim serial compatibility with 1.4 FCS
711
private static final long serialVersionUID = 7441350119349544720L;
712
713         // table of all instances in this class, used by readResolve
714
private static final Map JavaDoc instanceMap = new HashMap JavaDoc(18);
715         // Maps from Calendar constant (such as Calendar.ERA) to Field
716
// constant (such as Field.ERA).
717
private static final Field[] calendarToFieldMapping =
718                                              new Field[Calendar.FIELD_COUNT];
719
720         /** Calendar field. */
721         private int calendarField;
722
723         /**
724          * Returns the <code>Field</code> constant that corresponds to
725          * the <code>Calendar</code> constant <code>calendarField</code>.
726          * If there is no direct mapping between the <code>Calendar</code>
727          * constant and a <code>Field</code>, null is returned.
728          *
729          * @throws IllegalArgumentException if <code>calendarField</code> is
730          * not the value of a <code>Calendar</code> field constant.
731          * @param calendarField Calendar field constant
732          * @return Field instance representing calendarField.
733          * @see java.util.Calendar
734          */

735         public static Field ofCalendarField(int calendarField) {
736             if (calendarField < 0 || calendarField >=
737                         calendarToFieldMapping.length) {
738                 throw new IllegalArgumentException JavaDoc("Unknown Calendar constant "
739                                                    + calendarField);
740             }
741             return calendarToFieldMapping[calendarField];
742         }
743
744         /**
745          * Creates a Field with the specified name.
746          * calendarField is used to identify the <code>Calendar</code>
747          * field this attribute represents. Use -1 if this field does
748          * not have a corresponding <code>Calendar</code> value.
749          *
750          * @param name Name of the attribute
751          * @param calendarField Calendar constant
752          */

753         protected Field(String JavaDoc name, int calendarField) {
754             super(name);
755             this.calendarField = calendarField;
756             if (this.getClass() == DateFormat.Field JavaDoc.class) {
757                 instanceMap.put(name, this);
758                 if (calendarField >= 0) {
759                     // assert(calendarField < Calendar.FIELD_COUNT);
760
calendarToFieldMapping[calendarField] = this;
761                 }
762             }
763         }
764
765         /**
766          * Returns the <code>Calendar</code> field associated with this
767          * attribute. For example, if this represents the hours field of
768          * a <code>Calendar</code>, this would return
769          * <code>Calendar.HOUR</code>. If there is no corresponding
770          * <code>Calendar</code> constant, this will return -1.
771          *
772          * @return Calendar constant for this field
773          * @see java.util.Calendar
774          */

775         public int getCalendarField() {
776             return calendarField;
777         }
778
779         /**
780          * Resolves instances being deserialized to the predefined constants.
781          *
782      * @throws InvalidObjectException if the constant could not be
783          * resolved.
784          * @return resolved DateFormat.Field constant
785          */

786         protected Object JavaDoc readResolve() throws InvalidObjectException JavaDoc {
787             if (this.getClass() != DateFormat.Field JavaDoc.class) {
788                 throw new InvalidObjectException JavaDoc("subclass didn't correctly implement readResolve");
789             }
790
791             Object JavaDoc instance = instanceMap.get(getName());
792             if (instance != null) {
793                 return instance;
794             } else {
795                 throw new InvalidObjectException JavaDoc("unknown attribute name");
796             }
797         }
798
799         //
800
// The constants
801
//
802

803         /**
804          * Constant identifying the era field.
805          */

806         public final static Field ERA = new Field("era", Calendar.ERA);
807
808         /**
809          * Constant identifying the year field.
810          */

811         public final static Field YEAR = new Field("year", Calendar.YEAR);
812
813         /**
814          * Constant identifying the month field.
815          */

816         public final static Field MONTH = new Field("month", Calendar.MONTH);
817
818         /**
819          * Constant identifying the day of month field.
820          */

821         public final static Field DAY_OF_MONTH = new
822                             Field("day of month", Calendar.DAY_OF_MONTH);
823
824         /**
825          * Constant identifying the hour of day field, where the legal values
826          * are 1 to 24.
827          */

828         public final static Field HOUR_OF_DAY1 = new Field("hour of day 1",-1);
829
830         /**
831          * Constant identifying the hour of day field, where the legal values
832          * are 0 to 23.
833          */

834         public final static Field HOUR_OF_DAY0 = new
835                Field("hour of day", Calendar.HOUR_OF_DAY);
836
837         /**
838          * Constant identifying the minute field.
839          */

840         public final static Field MINUTE =new Field("minute", Calendar.MINUTE);
841
842         /**
843          * Constant identifying the second field.
844          */

845         public final static Field SECOND =new Field("second", Calendar.SECOND);
846
847         /**
848          * Constant identifying the millisecond field.
849          */

850         public final static Field MILLISECOND = new
851                 Field("millisecond", Calendar.MILLISECOND);
852
853         /**
854          * Constant identifying the day of week field.
855          */

856         public final static Field DAY_OF_WEEK = new
857                 Field("day of week", Calendar.DAY_OF_WEEK);
858
859         /**
860          * Constant identifying the day of year field.
861          */

862         public final static Field DAY_OF_YEAR = new
863                 Field("day of year", Calendar.DAY_OF_YEAR);
864
865         /**
866          * Constant identifying the day of week field.
867          */

868         public final static Field DAY_OF_WEEK_IN_MONTH =
869                      new Field("day of week in month",
870                                             Calendar.DAY_OF_WEEK_IN_MONTH);
871
872         /**
873          * Constant identifying the week of year field.
874          */

875         public final static Field WEEK_OF_YEAR = new
876               Field("week of year", Calendar.WEEK_OF_YEAR);
877
878         /**
879          * Constant identifying the week of month field.
880          */

881         public final static Field WEEK_OF_MONTH = new
882             Field("week of month", Calendar.WEEK_OF_MONTH);
883
884         /**
885          * Constant identifying the time of day indicator
886          * (e.g. "a.m." or "p.m.") field.
887          */

888         public final static Field AM_PM = new
889                             Field("am pm", Calendar.AM_PM);
890
891         /**
892          * Constant identifying the hour field, where the legal values are
893          * 1 to 12.
894          */

895         public final static Field HOUR1 = new Field("hour 1", -1);
896
897         /**
898          * Constant identifying the hour field, where the legal values are
899          * 0 to 11.
900          */

901         public final static Field HOUR0 = new
902                             Field("hour", Calendar.HOUR);
903
904         /**
905          * Constant identifying the time zone field.
906          */

907         public final static Field TIME_ZONE = new Field("time zone", -1);
908     }
909 }
910
Popular Tags